Unity 脚本中update,fixedupdate,lateupdate等函数的执行顺序

时间:2023-03-09 15:50:22
Unity 脚本中update,fixedupdate,lateupdate等函数的执行顺序

结论

通过一个例子得出的结论是:从先到后被执行的函数是 Awake->Start->FixedUpdate->Update->LateUpdate->OnGUI.

示例


接下来我们用一个例子来看一下。

首先,打开unity,新建一个项目。

Unity 脚本中update,fixedupdate,lateupdate等函数的执行顺序

然后,在默认的场景中新建三个cube并分别命名cube1、cube2、cube3,在Hierarchy中如下

Unity 脚本中update,fixedupdate,lateupdate等函数的执行顺序

因为,测试的东西跟位置大小都没关系,所以创建完cube就啥也不用管啦,直接看脚本。

接下来创建一个脚本,OderScript.cs

 using UnityEngine;
using System.Collections; public class OderScript : MonoBehaviour { // Use this for initialization
void Start () { Debug.Log(this.name+"'s Start()");
} bool hasUpdate = false;
// Update is called once per frame
void Update () { if (!hasUpdate)
{
Debug.Log(this.name + "'s Update()");
hasUpdate = true;
}
} void Awake()
{
Debug.Log(this.name + "'s Awake()");
} bool hasLateUpdate = false;
void LateUpdate()
{
if (!hasLateUpdate)
{
Debug.Log(this.name + "'s LateUpdate()");
hasLateUpdate = true;
}
} bool hasFixedUpdate = false;
void FixedUpdate()
{
if (!hasFixedUpdate)
{
Debug.Log(this.name + "'s FixedUpdate()");
hasFixedUpdate = true;
} } bool hasOnGUI = false;
void OnGUI()
{
if (!hasOnGUI)
{
Debug.Log(this.name + "'s OnGUI()");
hasOnGUI = true;
} }
}

最后给每个cube添加一个OderSript脚本,点击运行。结果如下:

Unity 脚本中update,fixedupdate,lateupdate等函数的执行顺序

结论

可以这样理解,每个game object的同名函数会被放到同一个线程中,而这些线程会根据某些规则按顺序执行。

本例中可以认为有N个执行同名函数的线程,这些线程的执行顺序是:Awake线程->Start线程->FixedUpdate线程->Update线程->LateUpdate线程->OnGUI线程.