-
Notifications
You must be signed in to change notification settings - Fork 1
/
Singleton.cs
executable file
·40 lines (35 loc) · 1.14 KB
/
Singleton.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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace UberTools
{
//Lazy on-demand creation singleton. Rarely useful in Unity, generally prefer ManualSingleton
//Use this by deriving from it e.g. class A : Singleton<A> {}
[AddComponentMenu("")]
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
static private T _Instance;
static public T Instance
{
get
{
if (_Instance == null)
{
System.Type t = typeof(T);
GameObject go = new GameObject(t.Name);
Object.DontDestroyOnLoad(go);
_Instance = go.AddComponent<T>();
var c = Instance as Singleton<T>;
c.OnSingletonCreate();
}
return _Instance;
}
private set { _Instance = value; }
}
static public bool Exists()
{
return _Instance != null;
}
virtual public void OnSingletonCreate() { }
}
}