Skip to content

Instantly share code, notes, and snippets.

@kazukitanaka0611
Created May 26, 2018 12:05
Show Gist options
  • Save kazukitanaka0611/3eb347f1318dca18be8dab93220b680b to your computer and use it in GitHub Desktop.
Save kazukitanaka0611/3eb347f1318dca18be8dab93220b680b to your computer and use it in GitHub Desktop.
Unity Singleton
using UnityEngine;
public abstract class Singleton<T> : MonoBehaviour where T : MonoBehaviour {
private static T instance;
public static T Instance {
get {
//Check if instance already exists
if (instance == null){
//if not, set instance to of type T
instance = FindObjectOfType<T>();
//If instance already exists and it's not this:
} else if (instance != FindObjectOfType<T>()){
//Then destroy this. This enforces our singleton pattern, meaning there can only ever be one instance of a GameManager.
Destroy(FindObjectOfType<T>());
}
//Sets this to not be destroyed when reloading scene
// DontDestroyOnLoad(FindObjectOfType<T>());
return instance;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment