The start function is in effect for every scene change

Hi unity users I translate this article with the help of google translation, so it may be problematic in writing.

I want to run a code only once when the game starts, but it works in every scene change when I write it to the start function.

How can I solve this problem?

Start is only called once for a particular object instance. If Start of your script is called each time a scene loads, that means you have a seperate object instance in each scene. Usually when you load a new scene, all objects from the old scene get destroyed automatically.

If you want your script to persist across multiple scenes you shouldn’t have one in each scene. Instead place that object in a loading scene which you only load once at the game start. Then use DontDestroyOnLoad on that gameobject so it doesn’t get destroyed when you load a new scene.

Another way would be to use static variables to remember the state.

private static m_Initialized = false;

void Start()
{
    if (!m_Initialized)
    {
        m_Initialized = true;
        // this is only run once
    }
}

You might want to use a Preload Scene.

Put any scripts you want active at all times during your project in this scene and load it automatically whenever you start your game.
This is not only to solve your problem but it is just generally a good idea to have one in your game.

Thanks for answers :slight_smile: