DontDestroy object to keep variables

How to keep some variables loaded when you change scenes or restart scenes ?
You can of course save it local on disk, but there’s more simple solution if it’s just some variables that don’t need to be kept forever (as player current health, that you need to keep when starting a new level)

You can create a gameObject that will store these values, and that’ll be undestroyable when you restart or load new scenes with the help of a little piece of code.

First declare it:

public static GameVars gamevars;

Then, in the awake method, we use the DontDestroyOnLoad()

void Awake(){
		if (gamevars == null) {
			DontDestroyOnLoad (gameObject);
			gamevars = this;
		} else if (gamevars != this) { //if already some gamevars loaded, destroy this one

Leave a Reply