Skip to content

Instantly share code, notes, and snippets.

@abdelfattahradwan
Last active November 2, 2019 11:16
Show Gist options
  • Save abdelfattahradwan/15d3c9f0626c0b8f43eefdc55f7d55d7 to your computer and use it in GitHub Desktop.
Save abdelfattahradwan/15d3c9f0626c0b8f43eefdc55f7d55d7 to your computer and use it in GitHub Desktop.
a simple generic singleton class for unity
using UnityEngine;
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
protected bool Persists { get; set; }
protected bool PreventDuplicates { get; set; }
public static T Instance { get; private set; }
protected virtual void Awake()
{
if (Instance == null)
{
Instance = this as T;
}
else if (Instance != null && Instance != this)
{
if (PreventDuplicates)
{
Destroy(Instance.gameObject);
}
Instance = this as T;
}
if (Persists)
{
DontDestroyOnLoad(gameObject);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment