简书链接:unity单例模式的样板代码
文章字数:189,阅读全文大约需要1分钟

plaintext
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

using UnityEngine;

/// <summary>
/// A static instance is similar to a singleton, but instead of destroying any new
/// instances, it overrides the current instance. This is handy for resetting the state
/// and saves you doing it manually
/// </summary>
public abstract class StaticInstance<T> : MonoBehaviour where T : MonoBehaviour
{
public static T Instance { get; private set; }
protected virtual void Awake() => Instance = this as T;
protected virtual void OnApplicationQuit()
{
Instance = null;
Destroy(gameObject);
}
}
/// <summary>
/// This transforms the static instance into a basic singleton. This will destroy any new
/// versions created, leaving the original instance intact
/// ///这将把静态实例转换成一个基本的单例。这将摧毁任何新的
///创建的版本,保留原来的实例不变
/// </summary>
public abstract class Singleton<T> : StaticInstance<T> where T : MonoBehaviour
{
protected override void Awake()
{
if (Instance != null) Destroy(gameObject);
base.Awake();
}
}

/// <summary>
//最后,我们有了一个持久版本的单例。这将通过现场生存
/// / / 负载。非常适合需要有状态、持久数据的系统类。或音频来源
///通过加载屏幕播放音乐,等等
/// </summary>
public abstract class PersistentSingleton<T> : Singleton<T> where T : MonoBehaviour
{
protected override void Awake()
{
base.Awake();
DontDestroyOnLoad(gameObject);
}
}

其中PersistentSingleton.DontDestroyOnLoad 是不会随场景变更而销毁,用于音频管理器。如果同一个节点下 存在单例模式,则会影响该节点所有脚本。