Unity Scripting Tutorials 要點記錄

這幾天經過Unity官網的Unity Scripting Tutorials的視頻學習Unity腳本,觀看的過程當中作了記錄。如今,整理了一下筆記,供本身之後和其餘初學者參考。編輯器

Awake和Start

  • Awake首先執行。一般用於創建組件間的引用,初始化。
  • Start在Awake以後和第一次Update以前執行,而且要求腳本enabled。只執行一次。

Updte和FixedUpdate

  • Update每幀一次,間隔不固定(受幀的處理時間影響),用於處理:

    • 非物理物體的運動
    • 獲取輸入
    • 定時器
  • FixedUpdate間隔固定,用於調整物理物體(剛體)。

enabled、setActive和Destroy

  • enabled控制禁用和啓用一個組件。禁用GameObject的renderer能夠隱藏物體,但碰撞體仍然存在。
  • setActive用於顯示和隱藏一個物體。
  • Destroy用於完全銷燬一個GameObject或組件。能夠加一個數值表示delay。

Translate和Rotate

使用這兩個方法控制物體運動。
Translate對應position:ide

transform.Translate(Vector3);   // Amount in each axis to move by

Rotate對應rotation:學習

transform.Rotate(Vector3,   // Axis around which to rotate
                 float)     // amount to rotate by

LookAt

transform.LookAt(target);

用於移動物體Z軸使之對準目標物體。
將其綁定到相機上能夠實現運動物體的跟蹤。3d

Lerp

用於平滑某種轉變。code

  • 空間移動:orm

    Vector3.Lerp(Vector3 from,  // 起點。一般應設爲當前座標
                 Vector3 to,    // 終點
                 float t);      // 0~1之間的值。值越大,返回值越接近終點,移動也越快。
  • 數值變換:視頻

    Mathf.Lerp(float from, float to, float t);
  • 顏色漸變:對象

    Color.Lerp(Color from, Color to, float t);

GetButton、GetKey和GetAxis

GetButton和GetKey的區別:ip

  1. 前者參數爲字符串,能夠經過設置面板更改字符串和對應按鍵的映射。
  2. 後者的參數爲KeyCode對象。

GetButton/Up/Down的區別:字符串

  1. Up按鍵彈起時爲true,其餘時爲false;
  2. 長按時GetButton每幀都返回true,而Down只有第一幀。

GetAxis(axisName)經過獲取某個軸的值來了解用戶的輸入。

  • axisName是字符串,能夠是「Horizontal」、「Vertical」。
  • 返回值爲0~1之間的值。
  • 在設置中能夠調節軸的參數,gravity控制返回0的速度,sensitivity控制離開0的速度。

OnMouseDown

鼠標在Collider或GUI組件上按下時調用該方法。
同類方法:

  • OnMouseDrag:按住不放
  • OnMouseEnter:進入
  • OnMouseExit:退出
  • OnMouseOver:在上面
  • OnMouseUp:釋放
  • OnMouseUpAsButton:按下和釋放做用於同一個對象

Instantiate

建立prefab的副本,返回對象的引用。
使用時先用代碼建立GameObject的變量,而後回到編輯器界面將prefab拖入變量中。

Invoke

調用名叫method的方法:

Invoke(method, delay);

每隔time重複調用method方法:

InvokeRepeating(method, delay, time);

取消Invoke:

CancelInvoke();

取消名叫method的Invoke:

CancelInvoke(method);

Coroutine

利用了C#的yield,來實如今屢次Update中執行一個行爲。
開始一個Coroutine:

StartCoroutine(IEnumerator routine);

或者接受一個string參數表示方法的返回IEnumerator的方法的名字,後面跟着參數。
例:

StartCoroutine(Func(param));
StartCoroutine("Func", param);

中止一個Coroutine,用StopCoroutine。一樣有兩種形式。

Quaternion

用來表示旋轉的類。講了三個內容:

1)

LookRotation(Vector3 forward);

返回使物體轉向forward方向的Quaternion。

2)

Slerp(Quaternion from, Quaternion to, float t);

旋轉角度。相比Lerp,在中間時快,兩頭時慢。

3)

Quaternion.identity是一個靜態變量,表示沒有旋轉。

相關文章
相關標籤/搜索