Last active
March 5, 2023 19:06
-
-
Save hasanbayatme/11ff050fc1affc733ea74a497ce42961 to your computer and use it in GitHub Desktop.
Best Singleton implementation in Unity, Combine it with preload scene pattern to achieve best implementation.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
public abstract class Singleton<T> : MonoBehaviour where T : Component | |
{ | |
#region Fields | |
/// <summary> | |
/// The instance. | |
/// </summary> | |
private static T instance; | |
#endregion | |
#region Properties | |
/// <summary> | |
/// Gets the instance. | |
/// </summary> | |
/// <value>The instance.</value> | |
public static T Instance | |
{ | |
get | |
{ | |
if ( instance == null ) | |
{ | |
instance = FindObjectOfType<T> (); | |
if ( instance == null ) | |
{ | |
GameObject obj = new GameObject (); | |
obj.name = typeof ( T ).Name; | |
instance = obj.AddComponent<T> (); | |
} | |
} | |
return instance; | |
} | |
} | |
#endregion | |
#region Methods | |
/// <summary> | |
/// Use this for initialization. | |
/// </summary> | |
protected virtual void Awake () | |
{ | |
if ( instance == null ) | |
{ | |
instance = this as T; | |
DontDestroyOnLoad ( gameObject ); | |
} | |
else | |
{ | |
Destroy ( gameObject ); | |
} | |
} | |
#endregion | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment