싱글톤은 객체의 인스턴스가 오직 하나인 디자인 패턴이다. 주로 게임매니저 스크립트에서 사용한다.
싱글톤이 필요한 경우가 많을 때 사용하면 유지 보수가 편하다.
public abstract class Singleton<T> : MonoBehaviour where T : Singleton<T>
{
[SerializeField]
private bool dontDestroy = true;
private static T instance = null;
public static T instance
{
get
{
if(instance ==null)
{
instance = InitManager<T>();
}
return instance;
}
}
protected static U InitManager<U>() where U : MonoBehaviour
{
GameObject go = null;
U obj = FindObjectOfType<U>();
if (obj == null)
{
go = new GameObject(typeof(U).Name);
go.AddComponent<U>();
}
else
{
go = obj.gameObject;
}
DontDestroyOnLoad(go);
return go.GetComponent<U>();
}
private void Awake()
{
if (instance == null)
{
if (dontDestroy)
{
Instance.Init();
}
else
{
instance = GetComponent<T>();
Init();
}
}
else
{
Destroy(gameObject);
}
}
'코린이 부트캠프 일상' 카테고리의 다른 글
유니티 Code Coverage 코드 잘 짜는 법 (0) | 2024.01.03 |
---|---|
Unity에서 몬스터 정보 관리하기: C# 및 스크립터블 오브젝트 활용 (0) | 2023.12.29 |
유니티 FSM -유한 상태 기계 (1) | 2023.12.26 |
유니티 클래스 상속 (1) | 2023.12.22 |
유니티 제이슨으로 데이터 저장하기 (0) | 2023.12.21 |