[unity]多脚本情况下update函数的执行顺序

有的时候,执行某些脚本时会有先后顺序的要求。unity是按什么顺序来执行脚本的?如何设置?

默认的执行顺序

官方文档里面有个很长的图:

Unity - Manual: Order of execution for event functions (unity3d.com)

 

根据文档,在单个脚本里,函数的执行顺序是是Awake、Start、Update……

如果用到了多个脚本,就会存在多个Awake,多个Start,这时候应该按什么顺序来?

根据这个网页[1]

先把所有脚本的Awake执行完,然后再执行所有脚本的Start……

那么,执行所有脚本start的时候,哪个脚本的start先执行?哪个脚本的start后执行?

根据这个网页[2] :

谁的start先执行,谁的start后执行,默认是有一个顺序的。

自定义执行顺序

但是,有的时候,默认的顺序不符合要求,需要自定义,这个怎么做?

比如,存在scriptA和scriptB,内容如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class scriptA : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        print("this is scriptA");
    }

    // Update is called once per frame
    void Update()
    {

    }
}

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class scriptB : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        print("this is script B");
    }

    // Update is called once per frame
    void Update()
    {

    }
}

按默认顺序的话,是先B后A:

但是实际使用的时候,需要先A后B,怎么办?如何设置?

打开窗口,点击加号,添加scriptA和scriptB,让scriptA排在scriptB的前面,就可以了。执行的时候,就会先执行A,再执行B了。

再执行,符合预期:

引用链接

[1]        Unity不同脚本之间的执行顺序-腾讯游戏学堂 (tencent.com) 

[2]        设置unity脚本的执行顺序-CSDN博客

相关链接

【Unity3D日常开发】Unity3D中实现不同脚本之间的执行顺序控制_unity update执行顺序-CSDN博客

unity如何手动更改脚本执行顺序_untiy 设置脚本执行顺序-CSDN博客 

猜你喜欢

转载自blog.csdn.net/averagePerson/article/details/134291090