내일배움캠프/[P5-Team.] Group3NotIncluded
[TIL 24.05.23] 제네릭 싱글톤
Charen_C
2024. 5. 23. 09:58
..
목 차
제네릭 싱글톤
Instance 프로퍼티
public static T Instance
{
get
{
// get instance of singleton
//인스턴스가 생성되었지만 미할당 상태.
if (instance == null)
{
instance = FindObjectOfType<T>();
}
//인스턴스가 생성된 적 없음.
if (instance == null)
{
GameObject gameObject = new GameObject(); //새 게임오브젝트
instance = gameObject.AddComponent<T>(); //컴포넌트 추가
gameObject.name = typeof(T).ToString(); //gameObject의 이름변경.
}
return instance;
}
}
스탠다드 과제의 싱글톤을 참고해 만들었다. 모든 방법이 같지만, 이름 부여 방식만 바뀌었다. $"{T}"로 했어도 되는지는 모르겠다...
Awake 함수로 파괴 방지
public void Awake()
{
if (instance == null)
{
//GetComponent<T>(); 대용.
//현재 객체를 T타입으로 캐스팅하여 instance에 할당, 실패시 null.
instance = this as T;
if (transform.parent != null)
{
DontDestroyOnLoad(transform.parent);
}
else
DontDestroyOnLoad(gameObject);
}
}
여기서 this as T는 instance를 할당해주는 것이다. GetComponent<T>()와 같은 역할을 해주되 더 간단하게 현재 스크립트를 찾아주는 역할로 알고있다.
또한, 부모 오브젝트가 있는 경우 부모도 파괴할 수 없게 한다.
마무리
.