Skip to content

Instantly share code, notes, and snippets.

@abeldantas
Last active October 27, 2023 08:21
Show Gist options
  • Save abeldantas/bb16c6c41d8a1f0e2630857532958d63 to your computer and use it in GitHub Desktop.
Save abeldantas/bb16c6c41d8a1f0e2630857532958d63 to your computer and use it in GitHub Desktop.
Basic singleton for C# Unity
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