Transform
Transform是Unity之中為數眾多元件(Component)之一,管理位置座標、旋轉角度以及大小比例等屬性。
物件位置向前(Z)移動一個單位
// from (0, 0, 0) to (0, 0, 1)
transform.TransformPoint (Vector3.forward);
RectTransform
用來儲存UGUI的位置、大小以及錨點等等資訊,基本上所有UGUI物件皆從屬於Canvas。
// 動態生成UGUI物件且位置不偏移 重點在於worldPositionStays要設成false
GameObject obj = (GameObject)Instantiate(uguiPrefab);
obj.SetParent (GameObject.Find("Canvas").transform, false);
// 調整RectTransform元件內屬性
GetComponent<RectTransform>().sizeDelta = new Vector2(width, height);
Ref: how-to-create-ui-from-scripting, transform-setparent, change-properties-of-rect-transform
Rigidbody
剛體,即具有實體的意思,如果需在腳本當中使用到OnCollision或OnTrigger等碰撞偵測的情況下,就必須加入此物件才行。
- Gravity Scale - 重力 (設為0則為無重力狀態)
- Fixed Angle - 修正角度 (勾起後就不會因為物理效果而偏移旋轉角度)
- Is Kinematic - 被碰撞後不會有任何物理效果。
// 按下Space之後角色跳躍,比起使用AddForce相對穩定。
bool pressJump = false;
void Update () {
if(Input.GetButtonDown("Jump")) { pressJump = true; }
}
void FixedUpdate () {
if(pressJump) {
pressJump = false;
rigidbody.velocity = new Vector2(forwardSpeed, jumpSpeed);
}
}
Trigger
觸發器,常用來製作開關、機關以及事件偵測等功能。
Collider
碰撞體,常用來製作地面、阻擋物以及碰撞偵測等功能。
AudioListener
負責場景收音(包括SFX、BGM)的元件。
// 暫停收音 == 靜音
AudioListener.pause = true;
AudioSource
承載音樂音效的元件。
- Mute - 靜音
- Play On Awake - 一開始立即播放
- Loop - 無限循環
- Pitch - 音調
- Volume - 音量
指定音樂片段並播放
AudioClip[] audioClips;
AudioSource audio = GetComponent<AudioSource>();
audio.clip = audioClips[0];
audio.Play();
Button (4.6+)
UGUI內建的按鈕元件。
- Interactable - 是否啟用。
- On Click() - 按下按鈕後的事件處理。(ex. 呼叫特定物件腳本中的函數)
using UnityEngine.UI;
// 停用按鈕
GetComponent<Button>().interactable = false;
Event Trigger (4.6+)
UGUI的事件偵測觸發器。
- PointerEnter (滑鼠移入UI)
- PointerExit (滑鼠移出UI)
Text (4.6+)
UGUI內建的文字方塊元件。
using UnityEngine.UI;
// 指定字串
GetComponent<Text>().text = "Hello World!";
Image (4.6+)
UGUI內建的圖片元件。
NavMeshAgent
自動尋路元件
Window > Navigation
- 將障礙物的navigation static屬性打勾。
- 將NavMeshAgent元件加到需要自動尋路的物件上。(如.敵人)
- 點擊Bake鈕燒出可走動區塊。
NavMeshAgent navAgent = GetComponent<NavMeshAgent>();
// 物件朝目標物位置移動
navAgent.SetDestination(target.transform.position);
提醒:跳躍或攀爬需要用到Off Mesh Link,需要Unity Pro。
Ref: Unity官方線上教學