Hello,
I’m new to Unity and still learning the best practices to using scripts. I’m trying to replicate the timer functionality as seen in Candy Crush. When the app opens, a timer starts until it reaches a target time, and gives the user a “life” and then starts again until all the lives are full.
My current code is implemented inside a script attacked to an object at the first Scene of the game. My timer updates inside the Update() method.
My problem is when the user loads another Scene, that timer is lost. My best guess is to create another script that is not attached to any scene. Does someone have an example ?
Thank You.
There are two ways that come into my mind of fixing this.
The first and probably easiest approach is to use a static variable for the timer. This way, the value does not get reset when you destroy or recreate the component.
Second, if for some reason you don’t like static variables and if there is no other component on this gameObject, you could just simply mark the object as “don’t destroy this when scene is changed”. The tricky part here is, that you also have to make sure to not load any scene where this object is part of after the first initial scene or else they will accumulate in your game.
To do this, simply call to DontDestroyOnLoad in your Awake:
void Awake()
{
DontDestroyOnLoad(this);
}