TIL(24-06-14) - 제네릭 싱글톤(Unity)

임재훈·2024년 6월 14일

Unity

목록 보기
17/20

제네릭 싱글톤

  • 싱글톤을 여러군데에서 사용할 때 유용하다
  • GameManager, SoundManager, CharacterManager ...
  • 싱글톤을 제네릭 형태(T)로 작성 해놓고 싱글톤이 필요한 클래스에서 상속받으면 돼서 간편하다.

사용법

using UnityEngine;

public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
    private static T instance;

    public static T Instance
    {
        get
        {
            if (instance == null)
            {
                instance = FindObjectOfType<T>();

                if(instance == null)
                {
                    GameObject obj = new GameObject(typeof(T).Name, typeof(T));
                    instance = obj.GetComponent<T>();
                }
            }
            return instance;
        }
    }

    public void Awake()
    {
        DontDestroyOnLoad(this.gameObject);
    }
}
  • where T : MonoBehaviour: T가 MonoBehaviour를 상속 받는 클래스여야 한다.
  • FindObjectOfType: 현재 씬에 인스턴스가 이미 있는지 찾는다.
  • 찾아봤는데 없으면 오브젝트를 새로 만든다.
  • 씬을 이동할 때도 오브젝트가 파괴되지 않는다.
public class GameManager : Singleton<GameManager>
{
	...
}
  • 싱글톤을 적용하고 싶은 클래스에 상속시켜서 원래 쓰던데로 사용하면 된다.
profile
초심을 잃지 말자!

0개의 댓글