You've successfully subscribed to Hacking with Unity - Learn how to create your own games
Great! Next, complete checkout for full access to Hacking with Unity - Learn how to create your own games
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info is updated.
Billing info update failed.

How to run unattached script in Unity

Ben Liu
Ben Liu

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

Ben Liu

Please feel free to contact me if you have any question. <br> https://t.me/NeedoneApp