본문 바로가기
프로그래밍/Unity

Unity MonoSingleton 모노싱글톤

by neive 2023. 2. 14.
728x90

https://gist.github.com/onevcat/6025819

 

Mono singleton Class. Extend this class to make singleton component.

Mono singleton Class. Extend this class to make singleton component. - MonoSingleton.cs

gist.github.com

 

 

 

using UnityEngine;

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

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

                if (instance == null)
                {
                    Debug.LogError($"Unable to find an instance of {typeof(T)}. Make sure there is at least one active object of type {typeof(T)} in the scene.");
                }
            }

            return instance;
        }
    }

    protected virtual void Awake()
    {
        if (instance == null)
        {
            instance = this as T;
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            Destroy(gameObject);
        }
    }
}

ChatGpt 가 추천해준 모노싱글턴..

 

그리고 추천해준걸 더 개선해서 달라고 하자 내놓은

 

using UnityEngine;

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

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

                if (instance == null)
                {
                    instance = new GameObject(typeof(T).ToString()).AddComponent<T>();
                }
            }

            return instance;
        }
    }

    protected virtual void Awake()
    {
        if (instance == null)
        {
            instance = this as T;
            DontDestroyOnLoad(gameObject);
        }
        else if (instance != this)
        {
            Destroy(gameObject);
        }
    }

    protected MonoSingleton() { }

    protected MonoSingleton(bool shouldCreateNewInstance)
    {
        if (shouldCreateNewInstance)
        {
            instance = null;
        }
    }
}
728x90

댓글