Last active
November 3, 2022 13:28
-
-
Save yagero/0922654a0645fbfd21b926ca048ed6a7 to your computer and use it in GitHub Desktop.
Control Unity's Script Execution Order by code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System; | |
#if UNITY_EDITOR | |
using UnityEditor; | |
#endif | |
public class ScriptExecutionOrder : Attribute | |
{ | |
public int order; | |
public ScriptExecutionOrder(int order) { this.order = order; } | |
} | |
#if UNITY_EDITOR | |
[InitializeOnLoad] | |
public class ScriptExecutionOrderManager | |
{ | |
static ScriptExecutionOrderManager() | |
{ | |
foreach (MonoScript monoScript in MonoImporter.GetAllRuntimeMonoScripts()) | |
{ | |
if (monoScript.GetClass() != null) | |
{ | |
foreach (var attr in Attribute.GetCustomAttributes(monoScript.GetClass(), typeof(ScriptExecutionOrder))) | |
{ | |
var newOrder = ((ScriptExecutionOrder)attr).order; | |
if (MonoImporter.GetExecutionOrder(monoScript) != newOrder) | |
MonoImporter.SetExecutionOrder(monoScript, newOrder); | |
} | |
} | |
} | |
} | |
} | |
#endif | |
/* | |
// USAGE EXAMPLE | |
[ScriptExecutionOrder(100)] | |
public class MyScript : MonoBehaviour | |
{ | |
// ... | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
[DefaultExecutionOrder(100)]
https://forum.unity.com/threads/undocumented-but-public-defaultexecutionorder-attribute.530618/