forked from AgileDevArt/AgileDevArt.github.io
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MonoSingleton.cs
26 lines (24 loc) · 851 Bytes
/
MonoSingleton.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
namespace UnityEngine
{
/// <summary>
/// This class creates it's own instance if not assigned to an existing gameobject
/// </summary>
public abstract class MonoSingleton<tt> : MonoBehaviour where tt : Component
{
static tt _instance;
public static tt Instance => _instance ?? SetInstance(new GameObject(typeof(tt).Name).AddComponent<tt>());
static tt SetInstance(tt instance)
{
if (_instance != instance)
DontDestroyOnLoad(_instance = instance);
return _instance;
}
protected virtual void Awake()
{
if (_instance == null)
SetInstance(this as tt ?? throw new System.InvalidCastException(typeof(tt).Name));
if (_instance != this)
Destroy(this.gameObject);
}
}
}