Created
May 26, 2018 12:05
-
-
Save kazukitanaka0611/3eb347f1318dca18be8dab93220b680b to your computer and use it in GitHub Desktop.
Unity Singleton
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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