Programmatically define execution order of scripts

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)

p.s. This answer was written a long time ago, before DefaultExecutionOrder existed. Unless you are writing some editor tool to manipulate the execution order, DefaultExecutionOrder attribute may be more simple/suitable solution.


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


you can use the attribute:

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

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

Tags:

C#

Events

Unity3D