hey guys new to unity here, i want to make a game and after searching for script with audio manager in it there is this piece of code that I don’t understand
void Awake() {
if (instance == null)
instance = this;
else if (instance != this)
Destroy(gameObject);
DontDestroyOnLoad(gameObject);
}
I read some web article in google but still doesn’t understand it, whats the use of this code and how does it works. thank you for your time answering
This is the basic way of creating a singleton. In other words, having a single instance of the class, and ensuring that any potential duplicates are prevented.
// This is the single instance of this script, accessed using
// ThisScript.instance from anywhere, at any time
public static MyScript instance;
// Runs when the GameObject is activated/initialized
void Awake()
{
// If instance is not already set...
if(instance == null)
{
// Set "instance" to be the currently-running script
instance = this;
}
// In case this script runs again on this same GameObject,
// Check whether the "instance" is THIS instance of this script...
else if(instance != this)
{
// Destroy any GameObject using this script that ISN'T the
// stored "instance" of the script
destroy(gameObject);
}
// Set this GameObject to persist between scenes
DontDestroyOnLoad(gameObject);
}
Then, to use it from another class…
// Rather than having to keep finding/saving references to the singleton...
MyScript script = GameObject.FindObjectOfType<MyScript>();
script.DoSomething();
// Instead, call the singleton version of that script...
MyScript.instance.DoSomething();