以编程方式定义脚本的执行顺序

Programmatically define execution order of scripts

通过编程方式将脚本添加到给定的游戏对象,这些脚本会按照添加的顺序执行吗?他们的活动 运行 会按照添加的顺序排列吗?

void Awake ()
{
    gameObject.AddComponent("Script_1");
    gameObject.AddComponent("Script_2");
}

如前所述here

By default, the Awake, OnEnable and Update functions of different scripts are called in the order the scripts are loaded (which is arbitrary). However, it is possible to modify this order using the Script Execution Order settings.

可参考执行顺序设置here

简短回答:否。但是您可以在设置中设置 Script Execution Order(菜单:编辑 > 项目设置 > 脚本执行顺序)或通过代码更改它:

// First you get the MonoScript of your MonoBehaviour
MonoScript monoScript = MonoScript.FromMonoBehaviour(yourMonoBehaviour);
 
// Getting the current execution order of that MonoScript
int currentExecutionOrder = MonoImporter.GetExecutionOrder(monoScript);
 
// Changing the MonoScript's execution order
MonoImporter.SetExecutionOrder(monoScript, x);
  1. Script Execution Order manipulation

  2. Changing Unity Scripts Execution Order from Code

  3. Change a script's execution order dynamically (from script)

p.s。这个答案是很久以前写的,在 DefaultExecutionOrder 存在之前。除非你正在编写一些编辑器工具来操纵执行顺序,DefaultExecutionOrder 属性可能更 simple/suitable 解决方案。

我在商店中看到的一些资产,例如 Cinemachine,在 .meta 文件中设置了 executionOrder 属性(例如,MyMonoBehavior.cs.meta)。我已经测试过,这确实有效(例如,将其从 0 更改为 200,然后右键单击并重新导入)。元文件似乎保存在包中,因此如果您要分发资产,将资产包与元文件一起放在商店中应该可行 (https://docs.unity3d.com/Manual/AssetPackages.html)。

您可以使用属性:

[DefaultExecutionOrder(100)]
public class SomeClass : MonoBehaviour
{
}

您也可以在编辑器脚本中实现这一点。添加 class 在加载时初始化并动态设置 MonoScripts 顺序。

[InitializeOnLoad]
public class SetExecutionOrder{

    static SetExecutionOrder(){
        MonoScript[] scripts = (MonoScript[])Resources.FindObjectsOfTypeAll(typeof(MonoScript));
        int order = -100;  //Set this to whatever order you want
        foreach(MonoScript script in scripts){
            if(script.GetClass() == typeof(MyMonoScriptType)){  //The type of the MonoScript who's order you want to change
                MonoImporter.SetExecutionOrder(script , order);
            }
        }
    }

}

这也将显示脚本执行顺序内的脚本 window。