summaryrefslogtreecommitdiff
path: root/WorldlineKeepers/Assets/Scripts/Common/SingletonMB.cs
blob: 458f6426085a106b437d35d9a196c6f19a1ca104 (plain)
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
using Newtonsoft.Json.Utilities;
using UnityEngine;
using WK;

public abstract class SingletonMB<T> : MonoBehaviour where T : class
{
    protected static T m_Instance;

    public static T Instance
    {
        get { return m_Instance; }
        set
        {
            if (m_Instance != null)
            {
                throw new System.ApplicationException("An instance was created duplicate!");
            }

            m_Instance = value;
        }
    }

    protected virtual void Awake()
    {
        //if (null != m_Instance)
        //{
        //    LogHelper.LogError(StringUtil.Concat("Exception: Duplicated Instance!! type is ", typeof(T).ToString(), ", plz send this error msg to hanjun!"));
        //}

        m_Instance = gameObject.GetComponent<T>();
    }

    /// <summary>
    /// CN: 加这个函数是为了同一个GameObject挂了多个Manager类,再OnDestroy里设置自己的单例为null
    /// </summary>
    protected virtual void OnDestroy()
    {
        //m_Instance = null;
        DoWhenOnDestroy();
    }

    protected virtual void DoWhenOnDestroy()
    {

    }

    public void ReleaseInstance()
    {
        if (m_Instance != null)
        {
            UnityEngine.Object.Destroy(this.gameObject);
            //m_Instance = null;
        }
        else
        {
            LogHelper.LogError("m_Instance is already null!! type is " + typeof(T).ToString());
        }
    }
}