Skip to content

Instantly share code, notes, and snippets.

@shaunsales
Created June 29, 2018 20:08
Show Gist options
  • Save shaunsales/1383242b5267cfc3c6ff03f40036f4c5 to your computer and use it in GitHub Desktop.
Save shaunsales/1383242b5267cfc3c6ff03f40036f4c5 to your computer and use it in GitHub Desktop.
using UnityEngine;
using System;
public class MonoSingleton<T> : MonoBehaviour where T : class
{
/// <summary>
/// Makes the object singleton not be destroyed automatically when loading a new scene.
/// </summary>
public bool DontDestroy;
private static MonoSingleton<T> _instance;
public static T Instance => _instance as T;
protected virtual void Awake()
{
if (_instance != null)
{
Destroy(gameObject);
}
else
{
_instance = this;
if (DontDestroy)
{
DontDestroyOnLoad(gameObject);
}
Initialize();
}
}
protected virtual void Initialize()
{
}
protected virtual void Shutdown()
{
}
protected virtual void OnDestroy()
{
if (_instance == this)
{
_instance = null;
Shutdown();
}
}
protected virtual void OnApplicationQuit()
{
if (_instance == this)
{
_instance = null;
Shutdown();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment