美文网首页
[Unity3D]Instantiate后的函数调用顺序测试

[Unity3D]Instantiate后的函数调用顺序测试

作者: 煎蛋的少年 | 来源:发表于2019-07-09 11:31 被阅读0次

    今天突然好奇一个问题,如果我 var go = GameObject.Instantiate(item)创建一个物体后,下一行马上调用go.xxx函数,那么到底和start/awake相比,函数调用顺序是怎样的呢。于是就开始测试。

    /// <summary>
    /// 被创建物体挂载的脚本
    /// </summary>
    public class ItemID : MonoBehaviour
    {
    
        private void Awake() {
            Debug.LogError("awake = " + this.gameObject.GetInstanceID());
            Debug.LogError("tick = " + DateTime.Now.Ticks);
        }
    
        // Use this for initialization
        void Start() {
            Debug.LogError("start = " + this.gameObject.GetInstanceID());
            Debug.LogError("tick = " + DateTime.Now.Ticks);
        }
    }
    

    分隔

    /// <summary>
    /// 创建物体的脚本
    /// </summary>
    public class TestStart : MonoBehaviour {
    
        public GameObject ob;
    
        // Use this for initialization
        void Start () {
            
        }
    
    
        void Update() {
            if (Input.GetKeyDown(KeyCode.A)) {
                GameObject go = GameObject.Instantiate(ob);
                Debug.LogError("nextline = " + go.GetInstanceID());
                Debug.LogError("tick = " + DateTime.Now.Ticks);
            }
        }
    
        //private void LateUpdate() {
        //    if (Input.GetKeyDown(KeyCode.A)) {
        //        GameObject go = GameObject.Instantiate(ob);
        //        Debug.LogError("nextline = " + go.GetInstanceID());
        //        Debug.LogError("tick = " + DateTime.Now.Ticks);
        //    }
        //}
    
        //private void FixedUpdate() {
        //    if (Input.GetKeyDown(KeyCode.A)) {
        //        GameObject go = GameObject.Instantiate(ob);
        //        Debug.LogError("nextline = " + go.GetInstanceID());
        //        Debug.LogError("tick = " + DateTime.Now.Ticks);
        //    }
        //}
    }
    

    为了避免一些遗漏的,我在三个update函数里分别作了测试,结果如下。

    测试结果:

    Update的结果


    update.png

    LateUpdate的结果


    lateupdate.png

    FixUpdate的结果


    fixupdate.png

    可以看得出,基本的顺序是 awake --- nextline --- start , 值得一提的是,在不同的update函数中,nextline 和 start 的时间差是不一样的,lateupdate和update的时间差相差不大,fixupdate的时间差就基本相等了,为此我又做了几次测试,fixupdate上nextline和start的时间差是不稳定的。猜测start函数是在每次update之前调用,而fixupdate有单独的计时器,得到这个结果也算合理。

    相关文章

      网友评论

          本文标题:[Unity3D]Instantiate后的函数调用顺序测试

          本文链接:https://www.haomeiwen.com/subject/tsztkctx.html