Last active
February 1, 2021 11:59
-
-
Save nooralibutt/9a21cb5db9c9522b0c4a to your computer and use it in GitHub Desktop.
Singleton Class Template Unity C#
This file contains 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 UnityEngine; | |
using System.Collections; | |
public class MySingletonClass : MonoBehaviour { | |
/// Static instance of Singleton Class which allows it to be accessed by any other script | |
private static MySingletonClass _instance = null; | |
/// <summary> | |
/// Gets the instance of the Singleton Class | |
/// If there is not an instance, Singleton Class will generate a gameObject "MySingletonClass" in current scene. | |
/// The instance game object will not be destroyed when load new scene. | |
/// </summary> | |
/// <value>The instance in the scene.</value> | |
public static MySingletonClass Instance { | |
get { | |
if (!_instance) { | |
_instance = FindObjectOfType(typeof(MySingletonClass)) as MySingletonClass; | |
if (!_instance) { | |
var obj = new GameObject("MySingletonClass"); | |
_instance = obj.AddComponent<MySingletonClass>(); | |
} else { | |
_instance.gameObject.name = "MySingletonClass"; | |
} | |
} | |
return _instance; | |
} | |
} | |
/// <summary> | |
/// Awake is called when the script instance is being loaded. | |
/// Awake is used to initialize any variables or game state before the game starts. | |
/// Awake is called only once during the lifetime of the script instance. | |
/// </summary> | |
void Awake() { | |
if (_instance == null) { | |
_instance = this; | |
// Sets this to not be destroyed when reloading scene | |
DontDestroyOnLoad(_instance.gameObject); | |
} else if (_instance != this) { | |
// If there's any other object exist of this type delete it | |
// as it's breaking our singleton pattern | |
Destroy(gameObject); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment