-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathManualSingleton.cs
executable file
·51 lines (44 loc) · 1.48 KB
/
ManualSingleton.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
41
42
43
44
45
46
47
48
49
50
51
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace UberTools
{
//Singleton that you manually place in a scene
//Use this by deriving from it e.g. class A : ManualSingleton<A> {}
[AddComponentMenu("")]
public class ManualSingleton<T> : MonoBehaviour where T : MonoBehaviour
{
public bool DestroyOnSceneChange = false;
static private T _Instance;
static public T Instance
{
get { return _Instance;}
private set {_Instance = value;}
}
static public bool Exists()
{
return _Instance != null;
}
/// In general, avoid overriding Awake, as it's called even when the Singleton is going to be deleted
/// Prefer OnSingletonCreate, which is called only when the Singleton is created
public virtual void Awake()
{
//If an instance of this already exists, delete this one.
if (Instance != null)
{
Object.Destroy(gameObject);
}
else
{
//Otherwise, tell this singleton to persist across scene changes, and call OnSingletonCreate
Instance = this as T;
if (!DestroyOnSceneChange)
{
Object.DontDestroyOnLoad(gameObject);
}
OnSingletonCreate();
}
}
virtual public void OnSingletonCreate() { }
}
}