unity执行顺序问题(如何再次执行start方法)

it2025-01-31  37

 

 分类: unity3D(66) 

unity执行顺序的文章已经很多了,其实不用看文章,那么麻烦,一张图就搞定了!

Look:

这里看到最特殊最常用的应该就是OnEnable了。OnEnable是在Awake之后Start之前执行的,特殊之处就是他会在物体隐藏之后再次显示时再次调用,而Start和Awake是做不到这一点!

为了证明宝宝没有说谎,请看实例:

下面有一个sphere(默认隐藏)和一个cube,在按钮上绑定一脚本quite点击按钮会让cube隐藏让sphere显示,而按键盘O键会让cube显示让sphere隐藏。在cube上绑定了一个脚本TESTONE。

 

按钮上绑定的脚本:

 

[csharp]  view plain  copy   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上的脚本;

 

[csharp]  view plain  copy   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方法。

 

[csharp]  view plain  copy   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 () {            }  }  

 

所以当遇到类似的情况就用宝宝的大法吧!哈哈哈!

转载于:https://www.cnblogs.com/w-wfy/p/7281761.html

相关资源:数据结构—成绩单生成器
最新回复(0)