There is the [RuntimeInitializeOnLoadMethod]
attribute. Excerpting from the documentation:
Allow a runtime class method to be initialized when a game is loaded at runtime without action from the user.
Methods marked [RuntimeInitializeOnLoadMethod]
are invoked after the game has been loaded. This is after the Awake
method has been invoked.
Note: The execution order of methods marked [RuntimeInitializeOnLoadMethod]
is not guaranteed.
// Create a non-MonoBehaviour class which displays
// messages when a game is loaded.
using UnityEngine;
class MyClass
{
[RuntimeInitializeOnLoadMethod]
static void OnRuntimeMethodLoad()
{
Debug.Log("After Scene is loaded and game is running");
}
}
The advantage of this approach is that the method will be called no matter what scene you start up in, and you don't need a specific object in that scene to handle this in Awake
or Start
. (And you also don't need to keep track of a flag to skip re-doing that work if play later returns to the same scene)