脚本的生命周期是非常重要的概念:Unity脚本从唤醒到销毁的过程。如下图:
初始阶段:
Awake():经验不多,我认为一般在工具类当中一般把初始的变量都写进该调用函数中。
Start():游戏初始化的时候使用。
物理阶段:
FixedUpdate(),OnCollisionXXX,OnTriggerXXX
输入事件:
OnMouseEnter(),--Over,--Exit,--Down,--Up
游戏逻辑:
Update(),LateUpdate()跟随中调用
场景渲染:
OnBecameVisible(),OnBecameInvisible()
结束阶段:
OnDisable(),OnDestroy(),OnApplicationQuit()
类的关系示意图如下:
查找组件的常用方法:GetComponent GetComponentInChidren GetComponentInParent等等
我们可以通过递归算法来写一个查找组件类:
public static Transform GetChild(Transform parentTF, string childName)
{
//在子物体中根据名称查找
Transform childTF = parentTF.Find(childName);
if (childTF != null) return childTF;
int count = parentTF.childCount;
for (int i = 0; i < count; i++)
{//将问题转移给子物体
childTF = GetChild(parentTF.GetChild(i), childName);
if (childTF != null)
return childTF;
}
return null;
}