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