一、添加单例模板类

 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

相关文章:

  • 2021-05-06
  • 2021-05-22
  • 2021-04-20
  • 2021-11-15
  • 2021-12-08
猜你喜欢
  • 2021-11-06
  • 2022-12-23
  • 2022-12-23
  • 2021-07-02
  • 2021-12-02
  • 2021-04-27
  • 2021-05-31
相关资源
相似解决方案