
版權聲明:本文為博主原創文章,未經博主允許不得轉載。
unity執行順序的文章已經很多了,其實不用看文章,那么麻煩,一張圖就搞定了!
Look:
這里看到最特殊最常用的應該就是OnEnable了。OnEnable是在Awake之后Start之前執行的,特殊之處就是他會在物體隱藏之后再次顯示時再次調用,而Start和Awake是做不到這一點!
為了證明寶寶沒有說謊,請看實例:
下面有一個sphere(默認隱藏)和一個cube,在按鈕上綁定一腳本quite點擊按鈕會讓cube隱藏讓sphere顯示,而按鍵盤O鍵會讓cube顯示讓sphere隱藏。在cube上綁定了一個腳本TESTONE。
按鈕上綁定的腳本:
- using UnityEngine;
- using System.Collections;
- public class quite : MonoBehaviour {
- public GameObject[] GO;
- // Use this for initialization
- void Start () {
- }
- // Update is called once per frame
- void Update () {
- if (Input.GetKey(KeyCode.O))//按鍵盤O鍵
- {
- // Debug.Log("cube出現");
- GO[1].SetActive(false);
- GO[0].SetActive(true);
- }
- }
- public void Clickthisbutton()//點擊按鈕
- {
- // Debug.Log("球出現");
- GO[0].SetActive(false);
- GO[1].SetActive(true);
- // Application.Quit();
- }
- }
然后再看在cube上的腳本;
- using UnityEngine;
- using System.Collections;
- public class TESTONE : MonoBehaviour {
- void Awake()
- {
- Debug.Log("Awake---1cube");
- }
- void OnEnable()
- {
- Debug.Log("OnEnable---1cube");
- }
- // Use this for initialization
- void Start () {
- Debug.Log("START--1cube");
- }
- // Update is called once per frame
- void Update () {
- }
- }
下面運行一下看下圖的Log;cube上log的執行順序很明顯(這些方法全都只執行一次):
然后點擊按鈕看下圖:cube已經隱藏,而sphere出現,所有的log還是原來的。
然后我們清理掉log,按鍵盤O鍵看下圖;看到cube再次顯示,但是log中只有OnEable方法執行了。怎么樣寶寶沒騙你們吧!!!
那么如何再次執行AWake 或Start方法呢?不用想我肯定是開始說廢話了,沒錯,那就是在OnEable方法里調用這兩個方法(如果是在其他腳本寫的OnEable方法那就要把那兩個改成Public方法了)!好吧,這樣其實在最開始就會執行兩次Start和Awake方法。
- using UnityEngine;
- using System.Collections;
- public class TESTONE : MonoBehaviour {
- public void Awake()
- {
- Debug.Log("Awake---1cube");
- }
- void OnEnable()
- {
- Debug.Log("OnEnable---1cube");
- Start();
- Awake();
- }
- // Use this for initialization
- public void Start () {
- Debug.Log("START--1cube");
- }
- // Update is called once per frame
- void Update () {
- }
- }
所以當遇到類似的情況就用寶寶的大法吧!哈哈哈!