一、添加单例模板类
![]()
1 using UnityEngine;
2
3 public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
4 {
5 private static T _instance;
6
7 private static object _lock = new object ();
8
9 public static T Instance
10 {
11 get {
12 if (applicationIsQuitting) {
13 return null;
14 }
15
16 lock (_lock) {
17 if (_instance == null) {
18 _instance = (T)FindObjectOfType (typeof(T));
19
20 if (FindObjectsOfType (typeof(T)).Length > 1) {
21 return _instance;
22 }
23
24 if (_instance == null) {
25 GameObject singleton = new GameObject ();
26 _instance = singleton.AddComponent<T> ();
27 singleton.name = "(singleton) " + typeof(T).ToString ();
28
29 DontDestroyOnLoad (singleton);
30 }
31 }
32
33 return _instance;
34 }
35 }
36 }
37
38 private static bool applicationIsQuitting = false;
39
40 public void OnDestroy ()
41 {
42 applicationIsQuitting = true;
43 }
44 }
View Code