Skip to content

Instantly share code, notes, and snippets.

@yagero
Last active November 3, 2022 13:28
Show Gist options
  • Save yagero/0922654a0645fbfd21b926ca048ed6a7 to your computer and use it in GitHub Desktop.
Save yagero/0922654a0645fbfd21b926ca048ed6a7 to your computer and use it in GitHub Desktop.
Control Unity's Script Execution Order by code
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
{
// ...
}
*/
@belzecue
Copy link

@XanNava
Copy link

XanNava commented Nov 3, 2022

What license is this under?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment