- Home /
Reliable way to detect when the game starts playing on a ScriptableObject?
I am using a Scriptable Object architecture, and as part of it I need what Awake claims to do according to the documentation
"Awake is called as the ScriptableObject script starts. This happens as the game is launched and is similar to MonoBehavior.Awake."
This doesn't seem to be true when playing. I have breakpoints on the Awake
function, and it gets called at random times in edit mode, and doesn't get called when switching to play mode at all.
I tried using OnEnable
instead, combined with a check of Application.IsPlaying
because OnEnable
gets called at random times in edit mode too, but at least this one does get called when starting play mode.
But here's the funny thing:
private void OnEnable()
{
Debug.Log("The game is " + (Application.isPlaying ? "playing" : "not playing"));
if (Application.isPlaying)
{
LevelLoaded(null);
}
}
During the OnEnable
call right after pressing the play button, Application.isPlaying
is false, despite the game being in play mode. The above Debug log will print The game is not playing
. It seems that the Application.isPlaying
gets enabled after OnEnable
is called.
At this point I have run out of ideas of ways I could get some kind of function call when the game starts.
I would think that OnEnable gets called before Application.IsPlaying is set to true. This is because OnEnable gets called when the related game object is loaded up / activated, which of course might well precede actual playing.
What are you trying to achieve? There is OnEnable, OnAwake and OnStart, all of which are personal to a specific game object. Do you need something more universal?
Answer by Nichathan · Mar 18 at 07:41 AM
There are 2 possible solutions here that I can think of. First, add a boolean that is set true in your Awake method and check that boolean before running the script. If there are things that must be ran, set it to run once the script starts if needed.
Second, Try to look at your Script Execution Order in the project settings this way you can control which scripts are called at which time. The path to get there is: Edit -> Project Settings (by the bottom) -> Script Execution Order (above the services dropdown)