unity執行順序問題(如何再次執行start方法)


 

 分類:

unity執行順序的文章已經很多了,其實不用看文章,那么麻煩,一張圖就搞定了!

Look:

這里看到最特殊最常用的應該就是OnEnable了。OnEnable是在Awake之后Start之前執行的,特殊之處就是他會在物體隱藏之后再次顯示時再次調用,而Start和Awake是做不到這一點!

為了證明寶寶沒有說謊,請看實例:

下面有一個sphere(默認隱藏)和一個cube,在按鈕上綁定一腳本quite點擊按鈕會讓cube隱藏讓sphere顯示,而按鍵盤O鍵會讓cube顯示讓sphere隱藏。在cube上綁定了一個腳本TESTONE。


 

按鈕上綁定的腳本:

 

[csharp]  view plain  copy
 
  1. using UnityEngine;  
  2. using System.Collections;  
  3.   
  4. public class quite : MonoBehaviour {  
  5.     public GameObject[] GO;  
  6.     // Use this for initialization  
  7.     void Start () {  
  8.       
  9.     }  
  10.       
  11.     // Update is called once per frame  
  12.     void Update () {  
  13.         if (Input.GetKey(KeyCode.O))//按鍵盤O鍵  
  14.         {  
  15.            // Debug.Log("cube出現");  
  16.             GO[1].SetActive(false);  
  17.             GO[0].SetActive(true);  
  18.         }  
  19.     }  
  20.     public void Clickthisbutton()//點擊按鈕  
  21.     {  
  22.       //  Debug.Log("球出現");  
  23.         GO[0].SetActive(false);  
  24.         GO[1].SetActive(true);  
  25.       //  Application.Quit();  
  26. }  
  27. }  

 

 

然后再看在cube上的腳本;

 

[csharp]  view plain  copy
 
  1. using UnityEngine;  
  2. using System.Collections;  
  3.   
  4. public class TESTONE : MonoBehaviour {  
  5.     void Awake()  
  6.     {  
  7.         Debug.Log("Awake---1cube");  
  8.     }  
  9.     void OnEnable()  
  10.     {  
  11.         Debug.Log("OnEnable---1cube");  
  12.     }  
  13.     // Use this for initialization  
  14.     void Start () {  
  15.         Debug.Log("START--1cube");  
  16.     }  
  17.       
  18.     // Update is called once per frame  
  19.     void Update () {  
  20.       
  21.     }  
  22. }  

 

 

下面運行一下看下圖的Log;cube上log的執行順序很明顯(這些方法全都只執行一次):

 

然后點擊按鈕看下圖:cube已經隱藏,而sphere出現,所有的log還是原來的。


然后我們清理掉log,按鍵盤O鍵看下圖;看到cube再次顯示,但是log中只有OnEable方法執行了。怎么樣寶寶沒騙你們吧!!!

那么如何再次執行AWake 或Start方法呢?不用想我肯定是開始說廢話了,沒錯,那就是在OnEable方法里調用這兩個方法(如果是在其他腳本寫的OnEable方法那就要把那兩個改成Public方法了)!好吧,這樣其實在最開始就會執行兩次Start和Awake方法。

 

[csharp]  view plain  copy
 
  1. using UnityEngine;  
  2. using System.Collections;  
  3.   
  4. public class TESTONE : MonoBehaviour {  
  5.  public void Awake()  
  6.     {  
  7.         Debug.Log("Awake---1cube");  
  8.     }  
  9.   void OnEnable()  
  10.     {  
  11.         Debug.Log("OnEnable---1cube");  
  12.         Start();  
  13.         Awake();  
  14.     }  
  15.     // Use this for initialization  
  16.     public void Start () {  
  17.         Debug.Log("START--1cube");  
  18.   
  19.     }  
  20.       
  21.     // Update is called once per frame  
  22.     void Update () {  
  23.       
  24.     }  
  25. }  


 

所以當遇到類似的情況就用寶寶的大法吧!哈哈哈!


免責聲明!

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



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