Reputation: 145
I'm new to the unity world. I created a soccer goal calculator, but when I change the scene and reopen it, the int value is resetting. Searching the web, I found that I need to use unitySingleton, but I don't understand how.
Can someone please help me understand how to implement unitySingleton
Thanks and sorry for my bad English.
Upvotes: 0
Views: 162
Reputation: 93
To keep up gameobjects through scenes you can use DontDestroyOnLoad(Object target);
what it does is pretty self explanatory all gameobjects that are targeted by this method are not destroyed when loading a new Scene.
Here is an example code of how you could possibly keep up values between scenes:
using UnityEngine;
public class Example: MonoBehaviour
{
/*this holds reference to the gameobject it self it needs to be static otherwise each
instance would have a reference to it self.*/
public static Example instance = null;
//a value (can be whatever)
public float counter = 0.0f;
void Awake()
{
/* if there an already existing Example gameobject (instance isn't null) destroy
the others*/
if (instance != null)
{
Destroy(gameObject);
}
/*the very first instance is kept as the instance and will run through all the
scenes keeping all values until the program is shutdown*/
else
{
DontDestroyOnLoad(gameObject); /*this will keep the gameobject "alive" through all scenes*/
instance = this; /*instance reference to this gameobject (the first one to exist)*/
}
}
void Update()
{
/*adding passing time to counter again this can be any behaviour you want and will
keep running through scenes AND the values wont be reset until you shutdown the
program*/
counter += Time.deltaTime;
}
}
Thus you have a gameobject that is kept through scenes AND keeps updating values as you wish.
Upvotes: 2