1.作为行为组件的脚本
using UnityEngine;
using System.Collections;
public class One: MonoBehaviour
{
void Update()
{
if (Input.GetKeyDown(KeyCode.R))
{
GetComponent<Renderer> ().material.color = Color.red;
}
if (Input.GetKeyDown(KeyCode.G))
{
GetComponent<Renderer>().material.color = Color.green;
}
if (Input.GetKeyDown(KeyCode.B))
{
GetComponent<Renderer>().material.color = Color.blue;
}
}
}
2.变量和函数
using UnityEngine;
using System.Collections;
public class Two: MonoBehaviour
{
int myInt = 5;
void Start ()
{
myInt = MultiplyByTwo(myInt);
Debug.Log (myInt);
}
int MultiplyByTwo (int number)
{
int ret;
ret = number * 2;
return ret;
}
}
3.约定和语法
using UnityEngine;
using System.Collections;
public class Three: MonoBehaviour
{
void Start ()
{
Debug.Log(transform.position.x);
if(transform.position.y <= 5f)
{
Debug.Log ("我要撞到地上了!");
}
}
}
4.if 语句
using UnityEngine;
using System.Collections;
public class Four: MonoBehaviour
{
float coffeeTemperature = 85.0f;
float hotLimitTemperature = 70.0f;
float coldLimitTemperature = 40.0f;
void Update ()
{
if(Input.GetKeyDown(KeyCode.Space))
TemperatureTest();
coffeeTemperature -= Time.deltaTime * 5f;
}
void TemperatureTest ()
{
// 如果咖啡的温度高于最热的饮用温度...
if(coffeeTemperature > hotLimitTemperature)
{
// ... 执行此操作。
print("Coffee is too hot.");
}
// 如果不是,但咖啡的温度低于最冷的饮用温度...
else if(coffeeTemperature < coldLimitTemperature)
{
// ... 执行此操作。
print("Coffee is too cold.");
}
// 如果两者都不是,则...
else
{
// ... 执行此操作。
print("Coffee is just right.");
}
}
}
5.Switch 语句
using UnityEngine;
using System.Collections;
public class Fiv: MonoBehaviour
{
public int intelligence = 5;
void Greet()
{
switch (intelligence)
{
case 5:
print ("Why hello there good sir! Let me teach you about Trigonometry!");
break;
case 4:
print ("Hello and good day!");
break;
case 3:
print ("Whadya want?");
break;
case 2:
print ("Grog SMASH!");
break;
case 1:
print ("Ulg, glib, Pblblblblb");
break;
default:
print ("Incorrect intelligence level.");
break;
}
}
}
6.循环
ForLoop
using UnityEngine;
using System.Collections;
public class ForLoop : MonoBehaviour
{
int numEnemies = 3;
void Start ()
{
for(int i = 0; i < numEnemies; i++)
{
Debug.Log("Creating enemy number: " + i);
}
}
}
WhileLoop
using UnityEngine;
using System.Collections;
public class WhileLoop : MonoBehaviour
{
int cupsInTheSink = 4;
void Start ()
{
while(cupsInTheSink > 0)
{
Debug.Log ("I've washed a cup!");
cupsInTheSink--;
}
}
}
DoWhileLoop
using UnityEngine;
using System.Collections;
public class DoWhileLoop : MonoBehaviour
{
void Start()
{
bool shouldContinue = false;
do
{
print ("Hello World");
}while(shouldContinue == true);
}
}
ForeachLoop
using UnityEngine;
using System.Collections;
public class ForeachLoop : MonoBehaviour
{
void Start ()
{
string[] strings = new string[3];
strings[0] = "First string";
strings[1] = "Second string";
strings[2] = "Third string";
foreach(string item in strings)
{
print (item);
}
}
}
7.作用域和访问修饰符
using UnityEngine;
using System.Collections;
public class ScopeAndAccessModifiers : MonoBehaviour
{
public int alpha = 5;
private int beta = 0;
private int gamma = 5;
private AnotherClass myOtherClass;
void Start ()
{
alpha = 29;
myOtherClass = new AnotherClass();
myOtherClass.FruitMachine(alpha, myOtherClass.apples);
}
void Example (int pens, int crayons)
{
int answer;
answer = pens * crayons * alpha;
Debug.Log(answer);
}
void Update ()
{
Debug.Log("Alpha is set to: " + alpha);
}
}
using UnityEngine;
using System.Collections;
public class AnotherClass
{
public int apples;
public int bananas;
private int stapler;
private int sellotape;
public void FruitMachine (int a, int b)
{
int answer;
answer = a + b;
Debug.Log("Fruit total: " + answer);
}
private void OfficeSort (int a, int b)
{
int answer;
answer = a + b;
Debug.Log("Office Supplies total: " + answer);
}
}
8.Awake 和 Start
using UnityEngine;
using System.Collections;
public class AwakeAndStart : MonoBehaviour
{
void Awake ()
{
Debug.Log("Awake called.");
}
void Start ()
{
Debug.Log("Start called.");
}
}
9.Update 和 FixedUpdate
using UnityEngine;
using System.Collections;
public class UpdateAndFixedUpdate : MonoBehaviour
{
void FixedUpdate ()
{
Debug.Log("FixedUpdate time :" + Time.deltaTime);
}
void Update ()
{
Debug.Log("Update time :" + Time.deltaTime);
}
}
10.启用和禁用组件
using UnityEngine;
using System.Collections;
public class EnableComponents : MonoBehaviour
{
private Light myLight;
void Start ()
{
myLight = GetComponent<Light>();
}
void Update ()
{
if(Input.GetKeyUp(KeyCode.Space))
{
myLight.enabled = !myLight.enabled;
}
}
}
11.激活游戏对象
ActiveObjects
using UnityEngine;
using System.Collections;
public class ActiveObjects : MonoBehaviour
{
void Start ()
{
gameObject.SetActive(false);
}
}
CheckState
using UnityEngine;
using System.Collections;
public class CheckState : MonoBehaviour
{
public GameObject myObject;
void Start ()
{
Debug.Log("Active Self: " + myObject.activeSelf);
Debug.Log("Active in Hierarchy" + myObject.activeInHierarchy);
}
}
12.Translate 和 Rotate
TransformFunctions
using UnityEngine;
using System.Collections;
public class TransformFunctions : MonoBehaviour
{
public float moveSpeed = 10f;
public float turnSpeed = 50f;
void Update ()
{
if(Input.GetKey(KeyCode.UpArrow))
transform.Translate(Vector3.forward * moveSpeed * Time.deltaTime);
if(Input.GetKey(KeyCode.DownArrow))
transform.Translate(-Vector3.forward * moveSpeed * Time.deltaTime);
if(Input.GetKey(KeyCode.LeftArrow))
transform.Rotate(Vector3.up, -turnSpeed * Time.deltaTime);
if(Input.GetKey(KeyCode.RightArrow))
transform.Rotate(Vector3.up, turnSpeed * Time.deltaTime);
}
}
13.Look At
using UnityEngine;
using System.Collections;
public class CameraLookAt : MonoBehaviour
{
public Transform target;
void Update ()
{
transform.LookAt(target);
}
}
14.线性插值
在制作游戏时,有时可以在两个值之间进行线性插值。这是通过 Lerp 函数来完成的。线性插值会在两个给定值之间找到某个百分比的值。例如,我们可以在数字 3 和 5 之间按 50% 进行线性插值以得到数字 4。这是因为 4 是 3 和 5 之间距离的 50%。
在 Unity 中,有多个 Lerp 函数可用于不同类型。对于我们刚才使用的示例,与之等效的将是 Mathf.Lerp 函数,如下所示:
// 在此示例中,result = 4
float result = Mathf.Lerp (3f, 5f, 0.5f);
Mathf.Lerp 函数接受 3 个 float 参数:一个 float 参数表示要进行插值的起始值,另一个 float 参数表示要进行插值的结束值,最后一个 float 参数表示要进行插值的距离。在此示例中,插值为 0.5,表示 50%。如果为 0,则函数将返回“from”值;如果为 1,则函数将返回“to”值。
Lerp 函数的其他示例包括 Color.Lerp 和 Vector3.Lerp。这些函数的工作方式与 Mathf.Lerp 完全相同,但是“from”和“to”值分别为 Color 和 Vector3 类型。在每个示例中,第三个参数仍然是一个 float 参数,表示要插值的大小。这些函数的结果是找到一种颜色(两种给定颜色的某种混合)以及一个矢量(占两个给定矢量之间的百分比)。
让我们看看另一个示例:
Vector3 from = new Vector3 (1f, 2f, 3f);
Vector3 to = new Vector3 (5f, 6f, 7f);
// 此处 result = (4, 5, 6)
Vector3 result = Vector3.Lerp (from, to, 0.75f);
在此示例中,结果为 (4, 5, 6),因为 4 位于 1 到 5 之间的 75% 处,5 位于 2 到 6 之间的 75% 处,而 6 位于 3 到 7 之间的 75% 处。
使用 Color.Lerp 时适用同样的原理。在 Color 结构中,颜色由代表红色、蓝色、绿色和 Alpha 的 4 个 float 参数表示。使用 Lerp 时,与 Mathf.Lerp 和 Vector3.Lerp 一样,这些 float 数值将进行插值。
在某些情况下,可使用 Lerp 函数使值随时间平滑。请考虑以下代码段:
void Update ()
{
light.intensity = Mathf.Lerp(light.intensity, 8f, 0.5f);
}
如果光的强度从 0 开始,则在第一次更新后,其值将设置为 4。下一帧会将其设置为 6,然后设置为 7,再然后设置为 7.5,依此类推。因此,经过几帧后,光强度将趋向于 8,但随着接近目标,其变化速率将减慢。请注意,这是在若干个帧的过程中发生的。如果我们不希望与帧率有关,则可以使用以下代码:
void Update ()
{
light.intensity = Mathf.Lerp(light.intensity, 8f, 0.5f * Time.deltaTime);
}
这意味着强度变化将按每秒而不是每帧发生。
请注意,在对值进行平滑时,通常情况下最好使用 SmoothDamp 函数。仅当您确定想要的效果时,才应使用 Lerp 进行平滑。
15.Destroy
删除脚本所挂载的物体
using UnityEngine;
using System.Collections;
public class DestroyBasic : MonoBehaviour
{
void Update ()
{
if(Input.GetKey(KeyCode.Space))
{
Destroy(gameObject);
}
}
}
删除其他物体
using UnityEngine;
using System.Collections;
public class DestroyOther : MonoBehaviour
{
public GameObject other;
void Update ()
{
if(Input.GetKey(KeyCode.Space))
{
Destroy(other);
}
}
}
删除物体上所存在的组件
using UnityEngine;
using System.Collections;
public class DestroyComponent : MonoBehaviour
{
void Update ()
{
if(Input.GetKey(KeyCode.Space))
{
Destroy(GetComponent<MeshRenderer>());
}
}
}
16.GetButton 和 GetKey
GetKey
using UnityEngine;
using System.Collections;
public class KeyInput : MonoBehaviour
{
public GUITexture graphic;
public Texture2D standard;
public Texture2D downgfx;
public Texture2D upgfx;
public Texture2D heldgfx;
void Start()
{
graphic.texture = standard;
}
void Update ()
{
bool down = Input.GetKeyDown(KeyCode.Space);
bool held = Input.GetKey(KeyCode.Space);
bool up = Input.GetKeyUp(KeyCode.Space);
if(down)
{
graphic.texture = downgfx;
}
else if(held)
{
graphic.texture = heldgfx;
}
else if(up)
{
graphic.texture = upgfx;
}
else
{
graphic.texture = standard;
}
guiText.text = " " + down + "\n " + held + "\n " + up;
}
}
GetButton
using UnityEngine;
using System.Collections;
public class ButtonInput : MonoBehaviour
{
public GUITexture graphic;
public Texture2D standard;
public Texture2D downgfx;
public Texture2D upgfx;
public Texture2D heldgfx;
void Start()
{
graphic.texture = standard;
}
void Update ()
{
bool down = Input.GetButtonDown("Jump");
bool held = Input.GetButton("Jump");
bool up = Input.GetButtonUp("Jump");
if(down)
{
graphic.texture = downgfx;
}
else if(held)
{
graphic.texture = heldgfx;
}
else if(up)
{
graphic.texture = upgfx;
}
else
{
graphic.texture = standard;
}
guiText.text = " " + down + "\n " + held + "\n " + up;
}
}
17.GetAxis
using UnityEngine;
using System.Collections;
public class AxisExample : MonoBehaviour
{
public float range;
public GUIText textOutput;
void Update ()
{
float h = Input.GetAxis("Horizontal");
float xPos = h * range;
transform.position = new Vector3(xPos, 2f, 0);
textOutput.text = "Value Returned: "+h.ToString("F2");
}
}
using UnityEngine;
using System.Collections;
public class DualAxisExample : MonoBehaviour
{
public float range;
public GUIText textOutput;
void Update ()
{
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
float xPos = h * range;
float yPos = v * range;
transform.position = new Vector3(xPos, yPos, 0);
textOutput.text = "Horizontal Value Returned: "+h.ToString("F2")+"\nVertical Value Returned: "+v.ToString("F2");
}
}
18.OnMouseDown
using UnityEngine;
using System.Collections;
public class MouseClick : MonoBehaviour
{
void OnMouseDown ()
{
rigidbody.AddForce(-transform.forward * 500f);
rigidbody.useGravity = true;
}
}
19.GetComponent
using UnityEngine;
using System.Collections;
public class UsingOtherComponents : MonoBehaviour
{
public GameObject otherGameObject;
private AnotherScript anotherScript;
private YetAnotherScript yetAnotherScript;
private BoxCollider boxCol;
void Awake ()
{
anotherScript = GetComponent<AnotherScript>();
yetAnotherScript = otherGameObject.GetComponent<YetAnotherScript>();
boxCol = otherGameObject.GetComponent<BoxCollider>();
}
void Start ()
{
boxCol.size = new Vector3(3,3,3);
Debug.Log("The player's score is " + anotherScript.playerScore);
Debug.Log("The player has died " + yetAnotherScript.numberOfPlayerDeaths + " times");
}
}
using UnityEngine;
using System.Collections;
public class AnotherScript : MonoBehaviour
{
public int playerScore = 9001;
}
using UnityEngine;
using System.Collections;
public class YetAnotherScript : MonoBehaviour
{
public int numberOfPlayerDeaths = 3;
}
20.DeltaTime
using UnityEngine;
using System.Collections;
public class UsingDeltaTime : MonoBehaviour
{
public float speed = 8f;
public float countdown = 3.0f;
void Update ()
{
countdown -= Time.deltaTime;
if(countdown <= 0.0f)
light.enabled = true;
if(Input.GetKey(KeyCode.RightArrow))
transform.position += new Vector3(speed * Time.deltaTime, 0.0f, 0.0f);
}
}
21.数据类型
using UnityEngine;
using System.Collections;
public class DatatypeScript : MonoBehaviour
{
void Start ()
{
//值类型变量
Vector3 pos = transform.position;
pos = new Vector3(0, 2, 0);
//引用类型变量
Transform tran = transform;
tran.position = new Vector3(0, 2, 0);
}
}
22.数组
using UnityEngine;
using System.Collections;
public class Arrays : MonoBehaviour
{
public GameObject[] players;
void Start ()
{
players = GameObject.FindGameObjectsWithTag("Player");
for(int i = 0; i < players.Length; i++)
{
Debug.Log("Player Number "+i+" is named "+players[i].name);
}
}
}
23.Invoke 延时
using UnityEngine;
using System.Collections;
public class InvokeScript : MonoBehaviour
{
public GameObject target;
void Start()
{
Invoke ("SpawnObject", 2);
}
void SpawnObject()
{
Instantiate(target, new Vector3(0, 2, 0), Quaternion.identity);
}
}
using UnityEngine;
using System.Collections;
public class InvokeRepeating : MonoBehaviour
{
public GameObject target;
void Start()
{
InvokeRepeating("SpawnObject", 2, 1);
}
void SpawnObject()
{
float x = Random.Range(-2.0f, 2.0f);
float z = Random.Range(-2.0f, 2.0f);
Instantiate(target, new Vector3(x, 2, z), Quaternion.identity);
}
}
24.枚举
using UnityEngine;
using System.Collections;
public class EnumScript : MonoBehaviour
{
enum Direction {North, East, South, West};
void Start ()
{
Direction myDirection;
myDirection = Direction.North;
}
Direction ReverseDirection (Direction dir)
{
if(dir == Direction.North)
dir = Direction.South;
else if(dir == Direction.South)
dir = Direction.North;
else if(dir == Direction.East)
dir = Direction.West;
else if(dir == Direction.West)
dir = Direction.East;
return dir;
}
}