Skip to content

Instantly share code, notes, and snippets.

@snlehton
Created August 27, 2018 11:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save snlehton/f2e43b0290a26c9239bad0ac0d8f78ec to your computer and use it in GitHub Desktop.
Save snlehton/f2e43b0290a26c9239bad0ac0d8f78ec to your computer and use it in GitHub Desktop.
using UnityEngine;
using UnityEngine.Assertions;
// Barebones Singleton class to be used with Unity
// Supports also Singleton instances coming from prefabs (PrefabSingleton).
// Prefabs need to reside in Resources folder and named [ComponentName].asset.
// If you have GameManager class, then you need Resources/GameManager.asset
public class Singleton<T> : MonoBehaviour where T:MonoBehaviour
{
// static singleton
private static T _instance;
public static T Instance
{
get
{
if (_instance != null)
{
return _instance;
}
var go = new GameObject(typeof(T).Name);
// Mark down this instance so it can be accessed
_instance = go.AddComponent<T>();
// Prevent this object from being destroyed when changing scenes
DontDestroyOnLoad(go);
return _instance;
}
}
}
public class PrefabSingleton<T> : MonoBehaviour where T:MonoBehaviour
{
// static singleton
private static T _instance;
public static T Instance
{
get
{
if (_instance != null)
{
return _instance;
}
var prefab = Resources.Load<T>(typeof(T).Name);
Assert.IsNotNull(prefab, string.Format("prefab {0} in resources not found", typeof(T).Name));
var go = Instantiate(prefab);
// Mark down this instance so it can be accessed
_instance = go.GetComponent<T>();
Assert.IsNotNull(_instance, string.Format("prefab {0} does not have component", typeof(T).Name));
// Prevent this object from being destroyed when changing scenes
DontDestroyOnLoad(go);
return _instance;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment