Last active
October 27, 2023 08:21
-
-
Save abeldantas/bb16c6c41d8a1f0e2630857532958d63 to your computer and use it in GitHub Desktop.
Basic singleton for C# Unity
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 System; | |
using UnityEngine; | |
public abstract class Singleton<T> : MonoBehaviour, IDisposable where T : Singleton<T> | |
{ | |
public static T Instance { get; protected set; } | |
void Awake() | |
{ | |
if ( Instance != null && Instance != this ) | |
{ | |
DestroyImmediate( gameObject ); | |
} | |
else | |
{ | |
Instance = ( T )this; | |
} | |
} | |
public virtual void Dispose() | |
{ | |
if (Instance == this) { | |
Instance = null; | |
} | |
} | |
protected virtual void OnDestroy() | |
{ | |
Dispose(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment