Tuesday, July 2, 2019

Unity: RuntimeInitializeOnLoadMethod - Order and Fault



RuntimeInitializeOnLoadMethod allows us to execute code at the start of a Unity program, without it being part of a Component.  This saves a lot of headache on special initializations and having to load things when you are not in the initializer scene. However, what is the exact order of these events, and are their any gotchas?

Order of events based on load type.
  1. After Assemblies Loaded
  2. Before Splash Screen
  3. Before Scene Load
  4. After Scene Load
    1. This is also the default, if you do not include a load type.
Example code:
using UnityEngine;

public class RuntimeInitializeLoadTypeTest
{
    [RuntimeInitializeOnLoadMethod()]
    public static void Default()
    {
        Debug.Log("Default");
    }

    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]
    public static void AfterAssembliesLoaded()
    {
        Debug.Log("AfterAssembliesLoaded");
    }

    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)]
    public static void AfterSceneLoad()
    {
        Debug.Log("AfterSceneLoad");
    }

    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
    public static void BeforeSceneLoad()
    {
        Debug.Log("BeforeSceneLoad");
    }

    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSplashScreen)]
    public static void BeforeSplashScreen()
    {
        Debug.Log("BeforeSplashScreen");
    }
}

Faults:

  • Only BeforeSceneLoad and AfterSceneLoad execute in the editor, and these will execute for each scene.  
    • This means using this for a 1 time execution is out, if you want to be able to test it in the IDE.  
    • Or, at least, your code has to remember if it has been executed before.
  • AfterAssembliesLoaded and BeforeSplashScreen do not execute in the IDE, so you cannot test them very easily, nor depend on them for typical debugging.

If you intend to use something for a one time execution, its then Before and After SceneLoad will work, but make sure the state will not be harmed by repeat calls or that only one scene will be in use in your app.

2 comments:

  1. The information I'm looking for. Thank you!

    ReplyDelete
  2. Using the RuntimeInitializeLoadTypeTest class in a multi-scene game in the Unity Editor, I noticed BeforeSceneLoad() and AfterSceneLoad() only ever get called once when both scenes are loaded. This seems to contradict your statement 'This means using this for a 1 time execution is out, if you want to be able to test it in the IDE.'

    ReplyDelete