2
\$\begingroup\$

I have a script that runs when the game is loading. That script sets the resolution, fullscreen, and loads other screen and important settings and applies them. I have the script attached to a gameObject in the main screen that have some game and scene scripts.

The problem is that everytime you return to the main scene, that script runs again causing several bugs.

Is there a way to run a script only at game startup?

\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

I wouldn't know a better way than the way you already do: By attaching it to a gameObject in your first scene and putting your setup code in Start().

As possible workarounds for the problems you encounter I would recommend:

  • Create an initialization scene which runs even before your main screen. The purpose of that scene is to run any initialization code and then load your main screen scene. You can also use that scene as a loading screen for the game.
  • Add a variable private static bool initialized to your initialization script. Then wrap the whole code of its Start method into if (!initialized) and end that code with initialized = true.
\$\endgroup\$
2
  • \$\begingroup\$ How is the bool helping when reloading the scene, do static variables keep their value between scenes after destroying and loading? \$\endgroup\$
    – Zibelas
    Commented Apr 19, 2021 at 6:19
  • \$\begingroup\$ @Zibelas Yes, static variables keep their value over the lifetime of the whole application. But that's not all that keyword means. See the official C# documentation for details. \$\endgroup\$
    – Philipp
    Commented Apr 19, 2021 at 8:15
6
\$\begingroup\$

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)

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .