Skip to content

Commit 35d9e61

Browse files
authored
Create Singleton.cs
1 parent 96cafec commit 35d9e61

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

Assets/Scripts/Utilities/Singleton.cs

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
using System.Collections;
2+
using System.Collections.Generic;
3+
using UnityEngine;
4+
5+
public 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+
}

0 commit comments

Comments
 (0)