0

I want to make a variable I can access in any unity scene.

I need this to see what level the player was in before death, so he can respawn at the level he died.

Please say the best method to do this if you can.

  • What is your level working with Unity? If you are just now starting, you can use a Singleton pattern (Best resource available is here: https://www.youtube.com/watch?v=mpM0C6quQjs) Having said that, if you are more experienced, I'd suggest going for a more robust system, utilizing scriptable objects. – Rhach Jun 30 '21 at 07:06

1 Answers1

1

There might be other ways of doing this but I have got to know these two.

Either: You can create a static class like this.

public static class Globals
{
       const int ScreenFadingIn = -1;
       const int ScreenIdle = 0;
       const int ScreenFadingOut   =   1;
       public static float ScreenFadeAlpha = 1.0f;
       public static int ScreenFadeStatus = ScreenFadingIn;
}

Code took from this thread C# Global Variables Available To All Scenes

OR: You can create a gameobject and attach the script which contains your desired variable and make that put line DontDestroyOnLoad(this);

Like this

void Awake() {
        if(Instance != null) {
            Destroy(this.gameObject);
            return;
        }
        Instance = this;
        DontDestroyOnLoad(this);
    }
Syed Mohib Uddin
  • 662
  • 4
  • 15
  • what does "DontDestroyOnLoad(this);" do? – Yash Raj Jun 30 '21 at 07:18
  • It doesn't destroy the gameobject when new scene will load you can see the game object under DontDestroyOnLoad(which is created in new loaded scene) in inspector where all gameobjects can be seen – Syed Mohib Uddin Jun 30 '21 at 07:25