1

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.

Yash Raj
  • 11
  • 2
  • 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

2

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
  • 718
  • 7
  • 16
  • 2
    what does "DontDestroyOnLoad(this);" do? – Yash Raj Jun 30 '21 at 07:18
  • 2
    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
  • This helped me a lot, however i don't understand why the if statement is needed? what will happen if i don't put the if statement. Also, what does "this" mean. – Adhrit Mar 21 '23 at 05:52
  • if keyword required because you don't want to re initialize instance otherwise it could create same object more than once, and this keyword simply pointing to the current class where code is placed. – Syed Mohib Uddin Mar 21 '23 at 09:38