How to run unattached script in Unity

· 1 min read
How to run unattached script in Unity

As we know, the script is yet another object/component in the Unity, therefore you can either attach the script to an game object or get called explicitly in order to run. However, Unity does provide a way to run the script directly with the help of RuntimeInitializeOnLoadMethod.

Example:

using UnityEngine;

public class InitExample {
    [RuntimeInitializeOnLoadMethod]
    static void OnRuntimeMethodLoad() {
        Debug.Log("script running");
    }
}

As long as you run the game, the script will be run and output the log.

More on the RuntimeInitializeOnLoadMethod

There are few options on the RuntimeInitializeOnLoadMethod attribute:

  • AfterAssembliesLoaded: Callback when all assemblies are loaded and preloaded assets are initialized.
  • AfterSceneLoad: After first Scene is loaded.
  • BeforeSceneLoad: Before first Scene is loaded.
  • BeforeSplashScreen: Immediately before the splash screen is shown.
  • SubsystemRegistration: Callback used for registration of subsystems

using UnityEngine;

public class InitExample {

    // 
    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
    static void OnBeforeSceneLoadRuntimeMethod()
    {
        Debug.Log("Before first scene");
    }

    //
    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)]
    static void OnAfterSceneLoadRuntimeMethod()
    {
        Debug.Log("After first scene 1");
    }

    // 
    [RuntimeInitializeOnLoadMethod]
    static void OnRuntimeMethodLoad()
    {
        Debug.Log("After first scene 2");
    }
}

The output:

Before first scene
After first scene 1
After first scene 2