少年修仙传客户端代码仓库
lcy
2024-12-16 a39c35fc6449430cd02bccb681c4a0a880e46cd9
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
using UnityEngine;
 
 
public class SingletonMonobehaviour<T> : MonoBehaviour where T : MonoBehaviour
{
 
    private static volatile T s_Instance = null;
    private static object s_Root = new object();
 
    public static T Instance
    {
        get
        {
            if (s_Instance == null)
            {
                lock (s_Root)
                {
                    T[] _instances = (T[])FindObjectsOfType(typeof(T));
                    string _name = typeof(T).Name;
                    if (_instances != null)
                    {
                        for (var i = 0; i < _instances.Length; i++)
                        {
                            Destroy(_instances[i].gameObject);
                            //Debug.Log("销毁了: " + _name);
                        }
                    }
                    //Debug.Log("创建了: " + _name);
                    GameObject _go = new GameObject();
                    _go.name = _name;
                    s_Instance = _go.AddComponent<T>();
                    DontDestroyOnLoad(_go);
                }
            }
            return s_Instance;
        }
    }
 
    public static bool IsValid()
    {
        return s_Instance != null;
    }
 
    protected virtual void OnDestroy()
    {
        // Debug.Log("执行了销毁");
        s_Instance = null;
    }
}