all repos — RPG @ e4654d09764a984539ba6cb6880cea7492aff7b6

Fully functional 3D turn based role playing game coded in C# and base Unity.

Assets/Scripts/Utility/Singleton.cs (view raw)

 1using System.Collections;
 2using System.Collections.Generic;
 3using UnityEngine;
 4
 5public abstract class Singleton<T> : MonoBehaviour where T : Component
 6{
 7
 8    #region Fields
 9
10    /// <summary>
11    /// The instance.
12    /// </summary>
13    private static T instance;
14
15    #endregion
16
17    #region Properties
18
19    /// <summary>
20    /// Gets the instance.
21    /// </summary>
22    /// <value>The instance.</value>
23    public static T Instance
24    {
25        get
26        {
27            if (instance == null)
28            {
29                instance = FindObjectOfType<T>();
30                if (instance == null)
31                {
32                    GameObject obj = new GameObject();
33                    obj.name = typeof(T).Name;
34                    instance = obj.AddComponent<T>();
35                }
36            }
37            return instance;
38        }
39    }
40
41    #endregion
42
43    #region Methods
44
45    /// <summary>
46    /// Use this for initialization.
47    /// </summary>
48    protected virtual void Awake()
49    {
50        if (instance == null)
51        {
52            instance = this as T;
53            DontDestroyOnLoad(gameObject);
54        }
55        else
56        {
57            Destroy(gameObject);
58        }
59    }
60
61    #endregion
62
63}