1. 腳本生命週期
1.1 MonoBehaviour LifeCycle
1.2 Awake() 和 Start()
Awake
- 初始化函數,在遊戲開始時系統自動調用
- 創建變量
- 無論腳本是否被激活都能被調用
Start
- 初始化函數,在Awake之後,Update之前
- 給變量賦值
- 只有腳本組件被激活才能被調用
1.3 Update() 和 FixedUpdate()
Update
- 每幀調用一次
- 用於非物理計算
FixedUpdate
- 每隔固定時間調用一次
- 用於物理運動計算
2. 變量的聲明與使用
public, [SerializedField] 可在調試面板看到
private, protected, [HideInInspector] 無法在面板看到
2.1 FindGameObject尋找場景實例
public GameObject gameObject;
void Start()
{
gameObject = GameObject.Find("Cube");
}
3. 腳本的響應事件與組件訪問
3.1 物體與組件的開關
gameObject.enabled
Active 和 InActive
gameObject.SetActive(false);
// 檢測active
obj.activeSelf.ToString();
obj.activeInHierarchy.ToString();
OnEnable, OnDisable, OnDestroy
3.2 Message 響應事件
MonoBehaviour API
啓動與刷新函數
啓動
Reset
- Awake
- Start
- 刷新
交互函數
- FixedUpdate
- Update
- LateUpdate
交互函數
- 物理 Physic
- 輸入 Input
- 渲染 Rendering
- 對象 Object
- 場景 Scene
- 程序 Application
- 網絡 Network
- 動畫 Animator
- 聲音 Audio
3.3 物理引擎與碰撞檢測
牛二公式
F = M * A
衝量公式
I = F * T = M * V
rb.AddForce(x, y, z, ForceMode)
ForceMode
- Acceleration (給加速度,需要在FixedUpdate調用)
- Force (給力)
碰撞檢測
- OnTriggerEnter(Collider other)
- OnTriggerStay(Collider other)
- OnTriggerEixt(Collider other)
- OnCollisionEnter(Collision other)
- OnCollision(Collision other)
- OnCollisionEixt(Collision other)
組件獲取
- GetComponent<>()
- GetComponentInParent<>()
- GetComponentInChildren<>()
4. Transform
- Position
- Rotation
- Scale
Transform API
座標系
- Right (local x axis)
- Up (local y axis)
- Forward (local z axis)
函數方法
- TransformPoint() -- 變換位置 從 local 到 world
- InverseTransformPoint() -- 變換位置 從 world 到 local
- TransformDirection() -- 變換方向 從 local 到 world
- InverseTransformDirection() -- 變換方向 從 world 到 local
位移
1. 變量
- position -- 相對於世界座標系
- localPosition -- 相對於父物體的座標系
2. 函數方法
- Translate(x, y, z, Space) // Space.Self & Space.World
- 第四個參數是指相對於什麼進行位移
3. 利用AnimationCurve Evaluate進行位移
4. 判斷兩點距離:Vector3.Distance(origin, target)
5. 獲取單位向量:vector.normalized
旋轉
歐拉角
transform.eulerAngle -- Vector3 // 相對於世界的 旋轉
transform.localEulerAngle -- Vector3 // 相對於父物體的 旋轉
方法
- transform.Rotate(float x, float y, float z, Vector3 Space)
- transform.Rotate(Vector3 axis, float angle, Vector3 Space)
- transform.RotateAround(Vector3 point, Vector3 axis, float angle) // 繞某個點的某個軸旋轉
- transform.LookAt(Vector3 position);
四元數
rotation -- Quaternion
localRotation -- Quaternion
方法
- Quaternion.LookRotation(Vector3 forward, Vector3 up) // 看向某個方向
- Quaternion.RotateTowards(origin, target, angle * Time.deltaTime); // 計算最終rotation
- Quaternion.FromToRotation(origin, target) // 返回兩方向的插值
- Slerp