CTIN 289 - Interactive Snippets Library

Powered by 🌱Roam Garden

Singletons


//a class with a static reference to itself that makes it globally accessible

//so any script can access it without getting a reference to it

public static ClassName instance; //static reference to self

ClassName.instance; //the way other scripts can access it

//so public methods and variables can be accessed by other scripts super easily

//the reference can only ever point to one instance of the script, but it’s possible to have more than one instance of the singleton in the scene, so it’s also important to make sure that the static reference matches the script instance:

private void Awake() {

if (instance == null) {

     instance = this; //if there’s no instance yet, make the instance this

}

else { Destroy(gameObject); } // if there’s already an instance, destroy this one

}

//this works great for stuff like audio managers and ui managers that need to be called from a bunch of different scripts