Unity Update与LateUpdate执行顺序之坑

  一看到这标题,大家可能会嗤之一笑,因为Update和LateUpdate的执行顺序应该是一件非常明了的事情,既然都叫LateUpdate了难道还能在Update之前执行不成?

回答这个问题之前,我们来看一张Unity的执行顺序图:

Unity Update与LateUpdate执行顺序之坑_第1张图片

  这边也明确的表明了Update一定在LateUpdate之前执行,我们可以先写些代码来测试一下:

public class OldCom : MonoBehaviour {

	// Use this for initialization
	void Start () {
        Debug.Log("OldCom Start Func Time is :" + Time.time);
        gameObject.AddComponent();
    }
	
	// Update is called once per frame
	void Update () {
        Debug.Log("OldCom Update Func Time is :" + Time.time);
    }

    void LateUpdate()
    {
        Debug.Log("OldCom LateUpdate Func Time is :" + Time.time);
    }

    public void OnClick()
    {
        gameObject.AddComponent();
        Debug.Log("OldCom OnClick Func Time is :" + Time.time);
    }
}
  这是第一个类,在累的Start、Update、LateUpdate、OnClick(点击button按钮)都有打印相应的时间,在start函数中增加一个新的component——NewCom,NewCom代码如下:

public class NewCom : MonoBehaviour {

    // Use this for initialization
    void Awake()
    {
        Debug.Log("---------------------NewCom Awake Func Time is :" + Time.time);
    }

    void Start()
    {
        Debug.Log("NewCom Start Func Time is :" + Time.time);
    }

    // Update is called once per frame
    void Update()
    {
        Debug.Log("NewCom Update Func Time is :" + Time.time);
    }

    void LateUpdate()
    {
        Debug.Log("NewCom LateUpdate Func Time is :" + Time.time);
    }
}
  与OldCom一样,也是将各个函数的时间节点打印出来。因为log量有点大,Awake的log是方便查看。

  在Start添加NewCom的结果也与预想的一样:

Unity Update与LateUpdate执行顺序之坑_第2张图片

  NewCom的相关代码在添加的那帧就执行了,并且Update确实在LateUpdate之前调用。但是,如果是在Onclick,也就是按钮按下的时候添加NewCom结果可就不一样了!如图:

Unity Update与LateUpdate执行顺序之坑_第3张图片

  在添加的那帧调用了NewCom的Start函数后紧接着依次调用了OldCom和NewCom的LateUpdate函数!NewCom的Update就这样被吃了!!等第一次调用NewCom的Update的时候时间已经来到了0.631,也就是说已经是下一帧的事了。

  有兴趣的同学可以再去试试,看看有没有其他情况下AddComponent会造成上述情况。不过不管如何,我们要记住的是,LateUpdate的代码不要和Update的逻辑有着强烈的先后逻辑关系,不然有可能造成某些非必先的bug,就不太好查咯。

  这个问题,已经反馈给Unity,不懂会不会在以后的版本修复这个问题。

你可能感兴趣的:(unity)