0%

【Unity】 单例模式的MonoBehaviour

之前开发HTCVive的时候在他的SDK里发现的,感觉这玩意写的很好,扒下来自己用了

源地址:https://github.com/ViveSoftware/ViveInputUtility-Unity/blob/develop/Assets/HTC.UnityPlugin/Utility/SingletonBehaviour.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
using System;
using UnityEngine;

[DisallowMultipleComponent]
public abstract class SingletonBehaviour<T> : MonoBehaviour where T : SingletonBehaviour<T>
{
private static T s_instance = null;
private static bool s_isApplicationQuitting = false;
private static object s_lock = new object();
private static Func<GameObject> s_defaultInitGOGetter;

private bool m_initialized;

public static bool Active { get { return !s_isApplicationQuitting && s_instance != null; } }

public bool IsInstance { get { return this == Instance; } }

protected bool IsApplicationQuitting { get { return s_isApplicationQuitting; } }

public static T Instance
{
get
{
Initialize();
return s_instance;
}
}

public static void Initialize()
{
lock (s_lock)
{
if (s_instance != null) { return; }

if (!Application.isPlaying || s_isApplicationQuitting) { return; }

var instances = FindObjectsOfType<T>();
if (instances.Length > 0)
{
s_instance = instances[0];
if (instances.Length > 1) { Debug.LogWarning("Multiple " + typeof(T).Name + " not supported!"); }
}

if (s_instance == null)
{
GameObject defaultInitGO = null;

if (s_defaultInitGOGetter != null)
{
defaultInitGO = s_defaultInitGOGetter();
}

if (defaultInitGO == null)
{
defaultInitGO = new GameObject("[" + typeof(T).Name + "]");
}

s_instance = defaultInitGO.AddComponent<T>();
}

if (!s_instance.m_initialized)
{
s_instance.m_initialized = true;
s_instance.OnSingletonBehaviourInitialized();
}
}
}

/// <summary>
/// Must set before the instance being initialized
/// </summary>
public static void SetDefaultInitGameObjectGetter(Func<GameObject> getter) { s_defaultInitGOGetter = getter; }

protected virtual void OnSingletonBehaviourInitialized() { }

protected virtual void OnApplicationQuit()
{
s_isApplicationQuitting = true;
}

protected virtual void OnDestroy()
{
if (!s_isApplicationQuitting && s_instance == this)
{
s_instance = null;
}
}
}