Skip to content

Instantly share code, notes, and snippets.

@takumifukasawa
Created January 21, 2023 06:51
Show Gist options
  • Save takumifukasawa/9519ed0f64abdf68608d098a3441b0d9 to your computer and use it in GitHub Desktop.
Save takumifukasawa/9519ed0f64abdf68608d098a3441b0d9 to your computer and use it in GitHub Desktop.
unity simple singleton component
using System;
using UnityEngine;
namespace Utilities
{
public class SingletonComponent<T> : MonoBehaviour where T : MonoBehaviour
{
private static T _instance;
public static T Instance
{
get
{
if (_instance == null)
{
_instance = (T)FindObjectOfType<T>();
}
return _instance;
}
}
protected void Awake()
{
if (_instance == null)
{
_instance = (T)FindObjectOfType<T>();
return;
}
if (this != _instance)
{
Destroy(this);
throw new Exception(string.Format("[SingletonComponent.Awake] exists singleton instance"));
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment