Skip to content

Instantly share code, notes, and snippets.

@nooralibutt
Last active February 1, 2021 11:59
Show Gist options
  • Save nooralibutt/9a21cb5db9c9522b0c4a to your computer and use it in GitHub Desktop.
Save nooralibutt/9a21cb5db9c9522b0c4a to your computer and use it in GitHub Desktop.
Singleton Class Template Unity C#
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