wangguan
2020-11-19 51e5211590b58df92c4bbdb8974b14f96276690a
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
using UnityEngine;
 
namespace Core.Utilities
{
    /// <summary>
    /// Singleton class,这种类型的Singleton赴作用,必须得在Unity中找一个Entity--Add Compoment,不然不会调用Awake.
    /// </summary>
    /// <typeparam name="T">Type of the singleton</typeparam>
    public abstract class Singleton<T> : MonoBehaviour where T : Singleton<T>
    {
        /// <summary>
        /// The static reference to the instance
        /// </summary>
        public static T instance { get; protected set; }
 
        /// <summary>
        /// Gets whether an instance of this singleton exists
        /// </summary>
        public static bool instanceExists
        {
            get { return instance != null; }
        }
 
        /// <summary>
        /// Awake method to associate singleton with instance
        /// </summary>
        protected virtual void Awake()
        {
            if (instanceExists)
            {
                Destroy(gameObject);
            }
            else
            {
                instance = (T) this;
            }
        }
 
        /// <summary>
        /// OnDestroy method to clear singleton association
        /// </summary>
        protected virtual void OnDestroy()
        {
            if (instance == this)
            {
                instance = null;
            }
        }
    }
}