Programmatically define execution order of scripts

我们两清 提交于 2020-12-25 02:53:53

问题


By programmatically adding scripts to a given game object, will these scripts execute in the order they were added? Will their events run in the order they were added?

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

回答1:


Short answer: No. But you can set Script Execution Order in the settings (menu: Edit > Project Settings > Script Execution Order) or change it from code:

// 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)

Recently I've also faced similar issue, and found this question without an answer. Thus decided to post useful information, hope it helps :)




回答2:


you can use the attribute:

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



回答3:


Some of the assets I've seen in the store, for example Cinemachine, set the executionOrder property in the .meta file (for example, MyMonoBehavior.cs.meta). I've tested and this indeed works (for example, change it from 0 to 200 then right-click and Reimport). It seems that the meta files are preserved in the package, so if you are distributing your asset, putting your asset package in the store with meta should work (https://docs.unity3d.com/Manual/AssetPackages.html).




回答4:


As mentioned 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.

Reference to Execution Order Setting can be found here




回答5:


You can also achieve this within editor scripts. Add class which initialized on load and set the MonoScripts Order dynamically.

[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);
            }
        }
    }

}

This will also show the script within the script execution order window.



来源:https://stackoverflow.com/questions/27928474/programmatically-define-execution-order-of-scripts

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!