기반, 해당씬에서만 유지되는 싱글톤
public class Singleton<T> : MonoBehaviour where T : Singleton<T>
{
private static T instance;
public static T Instance
{
get
{
if(instance == null)
{
instance = new GameObject(typeof(T).Name).AddComponent<T>();
}
return instance;
}
}
public static bool InstanceExist { get { return instance != null; } }
protected virtual void Awake()
{
if(InstanceExist)
{
Destroy(gameObject);
return;
}
instance = (T)this;
}
protected virtual void OnDestroy()
{
if(instance == this)
{
instance = null;
}
}
}
씬을 넘어가는 싱글톤
public class PersistentSingleton<T> : Singleton<T> where T : Singleton<T>
{
protected override void Awake()
{
base.Awake();
DontDestroyOnLoad(gameObject);
}
}
'유니티 소스코드' 카테고리의 다른 글
리소스 매니저 소스코드 (0) | 2025.03.27 |
---|---|
SFM(유한상태기계) 소스코드 (0) | 2025.03.26 |