Unity scene IF statement not working?

I’m using an IF statement that checks the current scene to see if I instantiated objects in them previously and if so recreate them in the same place when I return to that scene. However I’m having some grief with getting IF statement for “scene2”. Both scenes are have identical scripts in it that use SceneManager.GetActiveScene() and can recognise what scene is active ok, yet still the IF statement isn’t working because of the scene part of it…

 void Start() {

    /*Debug.Log(data.scene2_spheres.Count);
    Debug.Log(scenes_script.scene_Name);*/
    
    //This will check if spheres were created in the scene previously before going onto it
    //if (scenes_script.scene_Name == "scene1" && data.num_of_spheres1 >= 1)

    //THIS WORKS FINE

    if (scenes_script.scene_Name == "scene1" && data.scene1_spheres.Count >= 1)
    {
        Debug.Log("Is bigger than 1");
        //this will add up until it makes the list total of the spheres
        for (int i = 0; i < data.scene1_spheres.Count; i++)
        {
        
            //Instantiate(data.scene1_spheres<em>, data.scene1_vecs*, trans.rotation);*</em>

Instantiate(prefab, data.scene1_vecs*, trans.rotation);
_}
}
//Same for scene2…
//FOR SOME REASON IT DOESN’T RECOGNISE SCENE2 IS ACTIVE…
if (scenes_script.scene_Name == “scene2” && data.scene2_spheres.Count >= 1)
{
Debug.Log(“Is bigger than 1”);
for (int i = 0; i < data.scene2_spheres.Count; i++)
{_
Instantiate(prefab, data.scene2_vecs, trans.rotation);
_}
}
}*

Haven’t done much scripting with scenes but a bit stumped here._

This is probably a script execution order issue. When you load the new scene you are relying on the two Start functions happening in the right order. For your code to work you need things to happen in this order:

  • scenes.Start() // This sets the value of scene_Name
  • OtherClass.Start() // This uses the value of scene_Name (I don’t know what the class in the original question is called)

By default you can’t rely on the Start functions happening in the right order. However Unity does allow you to define an order. See Unity - Manual: Script Execution Order Settings

In your case you want to add the scenes class to the custom order list and give it a negative value to ensure that it runs first.