unity脚本执行顺序

这篇博客详细介绍了Unity中单个GameObject和多个脚本的执行顺序,包括Awake、OnEnable、Start、FixedUpdate、Update、LateUpdate等生命周期函数。同一GameObject上,脚本按类名顺序执行,而父子关系的GameObject则遵循显示层次,父级先执行。还提到了可以通过Inspector调整脚本执行顺序,并提供了一个OrderTest示例脚本来演示各种函数的打印顺序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

unity5单个gameobject各函数的执行顺序,跟unity3不同:
Awake(Awake是先于OnEnable的,不管是否启用,都会执行)
OnEnable
Start
FixedUpdate 
WaitForFixedUpdate 
Update 
LateUpdate
YieldNull
OnWillRenderObject
OnGUI
WaitForEndOfFrame
WaitForSeconds
OnDisable 

同一个GameObject上的多个脚本是按类名顺序执行的:
AScript.Start
BScript.Start
AScript.Update
BScript.Update
......

父子关系的多个gameobject各函数的执行顺序:
兄弟关系的也一样,总的思想是显示在上层的gameobject的脚本先执行,显示在底层的gameobject后执行,体现了叶子依赖根的思想。

all.AwakeAndOnEnable(){
child.Awake
child.OnEnable
parent.Awake
parent.OnEnable
}

all.Start(){
//以后的都是这样
child.Start
parent.Start
}

……

all.OnWillRenderObject(){
//这里是个特例,肯定是父亲先显示,子才能显示
parent.OnWillRenderObject
child.OnWillRenderObject
}

之所以设计出这样是因为一般Manager脚本挂在父亲上,在父亲的start里面可以设置子女的参数,子代的脚本一般不要依赖父亲的脚本了,如果这么做的话,就要在子代脚本里面做延迟处理了,不推荐。

http://dl2.iteye.com/upload/attachment/0094/8075/0f2eac68-9b75-31a0-b489-bd9052ad32fb.png

注意:可以在Inspector中手动调节脚本执行顺序。

using UnityEngine;
using System.Collections;

public class OrderTest : MonoBehaviour {

    public string name = string.Empty;


    void Awake () 
    {
        Debug.Log(name+":Awake");
    }

    void OnEnable () {
        Debug.Log (name+":OnEnable");
    }

    void Start () {
        Debug.Log (name+":Start");
        StartCoroutine (YieldNull());
        StartCoroutine (FWaitForSeconds());
        StartCoroutine (FWaitForFixedUpdate ());
        StartCoroutine (FWaitForEndOfFrame ());
    }

    void FixedUpdate(){
        Debug.Log (name+":FixedUpdate");
    }

    IEnumerator FWaitForFixedUpdate(){
        yield return new WaitForFixedUpdate ();
        Debug.Log (name+":WaitForFixedUpdate");
    }

    void Update () {
        Debug.Log (name+":Update");
    }

    void LateUpdate(){
        Debug.Log (name+":LateUpdate");
    }

    IEnumerator YieldNull(){
        yield return null;
        Debug.Log (name+":YieldNull");
    }

    void OnWillRenderObject(){
        Debug.Log (name+":OnWillRenderObject");
    }

    void OnGUI(){
        Debug.Log (name+":OnGUI");
    }

    IEnumerator FWaitForEndOfFrame(){
        yield return new WaitForEndOfFrame ();
        Debug.Log (name+":WaitForEndOfFrame");
    }

    IEnumerator FWaitForSeconds(){
        yield return new WaitForSeconds(1);
        Debug.Log (name+":WaitForSeconds");
    }

    void OnDisable(){
        Debug.Log (name+":OnDisable");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值