게임엔진/유니티

[게임엔진/유니티] MonoSingleton을 배우고 혼자 정리해본 글

susot 2024. 10. 15. 00:03

using UnityEngine;

public class MonoSingleton<T> : MonoBehaviour where T : MonoBehaviour
{
    private static T _instance = null;
    private static bool IsDestroyed = false;

    public static T Instance
    {
        get
        {
            if (IsDestroyed)
                _instance = null;

            if (_instance == null)
            {
                _instance = GameObject.FindAnyObjectByType<T>();

                if (_instance == null)
                    Debug.LogError($"{typeof(T).Name} singleton is not exist");
                else
                    IsDestroyed = false;

                DontDestroyOnLoad(_instance.gameObject);
            }

            return _instance;
        }
    }

    private void OnDisable()
    {
        IsDestroyed = true;
    }
}

 

MonoSingleton은 MonoBehaviour를 상속받는 모든 싱글톤에서 쓸 수 있다.

MonoSingleton을 쓰면 싱글톤 패턴을 사용할때마다 instance 만들고 null 체크할 필요 없이

 

public class GameManager : MonoSingleton<GameManager>

상속 받아서 사용할 수 있어서 편리하다

 

무엇보다 인스턴스를 만들 필요 없이

GameManager.Instance로 바로 사용이 가능하다.