Created
June 29, 2018 20:08
-
-
Save shaunsales/1383242b5267cfc3c6ff03f40036f4c5 to your computer and use it in GitHub Desktop.
This file contains 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; | |
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