Develoment/Unity
[유니티] Generic singleton(제네릭 싱글톤) 클래스 제작
Seo_re:
2022. 1. 26. 00:11
반응형
제네릭 싱글톤(Generic singleton)
- 싱글톤 : 객체의 인스턴스가 오직 하나인 디자인 패턴
- Generic class : 데이터 형식을 일반화한 클래스를 말한다.
코드
using UnityEngine;
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);
}
}
protected abstract void Init();
}
- DontDestroyOnLoad를 사용하지 않으려면 인스펙터 창에서 해당 bool값을 false로 변경해준다.
- Init 함수를 추상 함수로 지정해서 싱글톤으로 지정할 클래스의 초기화를 Init에서 하도록 유도한다.
반응형