In this example, a private static instance of the class is declared at its beginning.
The value of a static field is shared between instances, so if a new instance of this class gets created the if
will find a reference to the first Singleton object, destroying the new instance (or its game object).
using UnityEngine;
public class SingletonExample : MonoBehaviour {
private static SingletonExample _instance;
void Awake(){
if (_instance == null){
_instance = this;
DontDestroyOnLoad(this.gameObject);
//Rest of your Awake code
} else {
Destroy(this);
}
}
//Rest of your class code
}