Skip to content

Instantly share code, notes, and snippets.

@BrodyB
Created January 22, 2017 18:33
Show Gist options
  • Save BrodyB/f137ecedcc1f2513c00193e1050d6050 to your computer and use it in GitHub Desktop.
Save BrodyB/f137ecedcc1f2513c00193e1050d6050 to your computer and use it in GitHub Desktop.
Reusable singleton base class for use in Unity
using UnityEngine;
using System.Collections;
/// <summary>
/// Singleton manager base class.
/// </summary>
public class Singleton<T> : MonoBehaviour where T : Singleton<T>
{
static T _instance;
public static T Instance
{
get
{
if (_instance == null)
{
_instance = GameObject.FindObjectOfType<T>();
if (_instance == null)
{
GameObject newObj = new GameObject("[" + typeof(T).Name + "]");
_instance = newObj.AddComponent<T>();
}
}
return _instance;
}
}
protected virtual void Awake ()
{
_instance = (T)this;
}
}
//
// To make a class a singleton that uses this implementation,
// do the following:
/*
public class SingletonExample : Singleton<SingletonExample>
{
// Awake can be overridden but still do everything
// done in its base Awake function first like so:
protected override void Awake ()
{
base.Awake();
// Do your other Awake tasks
}
}
*/
// Your singleton can now be grabbed from anywhere by accessing:
// SingletonExample.Instance
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment