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

 

结论

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

 

示例


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

 

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

 

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

 

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

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

 

 1 using UnityEngine;
 2 using System.Collections;
 3 
 4 public class OderScript : MonoBehaviour {
 5 
 6     // Use this for initialization
 7     void Start () {
 8 
 9         Debug.Log(this.name+"'s Start()");
10     }
11 
12     bool hasUpdate = false;
13     // Update is called once per frame
14     void Update () {
15 
16         if (!hasUpdate)
17         {
18             Debug.Log(this.name + "'s Update()");
19             hasUpdate = true;
20         }
21     }
22 
23     void Awake()
24     {
25         Debug.Log(this.name + "'s Awake()");
26     }
27 
28     bool hasLateUpdate = false;
29     void LateUpdate()
30     {
31         if (!hasLateUpdate)
32         {
33             Debug.Log(this.name + "'s LateUpdate()");
34             hasLateUpdate = true;
35         }
36     }
37 
38     bool hasFixedUpdate = false;
39     void FixedUpdate()
40     {
41         if (!hasFixedUpdate)
42         {
43             Debug.Log(this.name + "'s FixedUpdate()");
44             hasFixedUpdate = true;
45         }
46             
47     }
48 
49     bool hasOnGUI = false;
50     void OnGUI()
51     {
52         if (!hasOnGUI)
53         {
54             Debug.Log(this.name + "'s OnGUI()");
55             hasOnGUI = true;
56         }
57            
58     }
59 }

 

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

 

结论

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

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

posted @ 2014-06-09 13:35  追峰人  阅读(8563)  评论(0编辑  收藏  举报