728x90
https://gist.github.com/onevcat/6025819
using UnityEngine;
public class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
{
private static T instance;
public static T Instance
{
get
{
if (instance == null)
{
instance = FindObjectOfType<T>();
if (instance == null)
{
Debug.LogError($"Unable to find an instance of {typeof(T)}. Make sure there is at least one active object of type {typeof(T)} in the scene.");
}
}
return instance;
}
}
protected virtual void Awake()
{
if (instance == null)
{
instance = this as T;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}
}
ChatGpt 가 추천해준 모노싱글턴..
그리고 추천해준걸 더 개선해서 달라고 하자 내놓은
using UnityEngine;
public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
{
private static T instance;
public static T Instance
{
get
{
if (instance == null)
{
instance = FindObjectOfType<T>();
if (instance == null)
{
instance = new GameObject(typeof(T).ToString()).AddComponent<T>();
}
}
return instance;
}
}
protected virtual void Awake()
{
if (instance == null)
{
instance = this as T;
DontDestroyOnLoad(gameObject);
}
else if (instance != this)
{
Destroy(gameObject);
}
}
protected MonoSingleton() { }
protected MonoSingleton(bool shouldCreateNewInstance)
{
if (shouldCreateNewInstance)
{
instance = null;
}
}
}
728x90
'프로그래밍 > Unity' 카테고리의 다른 글
Unity - 유용한 개발 에셋 유틸 : GPU Instancer (0) | 2023.04.28 |
---|---|
Object Pool 에 들어간 class 의 동작 (0) | 2023.03.21 |
Unity - Addressable Patch Download (0) | 2022.10.11 |
유니티 네트워크 상태 얻기 (0) | 2022.08.12 |
유니티 - 슬립 모드 (0) | 2022.08.10 |
댓글