Created
January 21, 2023 06:51
-
-
Save takumifukasawa/9519ed0f64abdf68608d098a3441b0d9 to your computer and use it in GitHub Desktop.
unity simple singleton component
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; | |
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