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線程.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM