Skip to content

싱글톤 사용 관련 제안 #7

@jk96491

Description

@jk96491

아래와 같은 사용도 고려 해보세요.
훨씬 간편할거에요!

using UnityEngine;

public class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
{
    private static T _instance;
    private static object _lock = new object();
    private static bool _applicationIsQuitting = false;

    public static T Instance
    {
        get
        {
            if (_applicationIsQuitting)
            {
                Debug.LogWarning($"[Singleton] {typeof(T)} 인스턴스는 앱 종료 중이므로 반환되지 않습니다.");
                return null;
            }

            lock (_lock)
            {
                if (_instance == null)
                {
                    _instance = FindObjectOfType<T>();

                    if (_instance == null)
                    {
                        GameObject singletonObject = new GameObject(typeof(T).Name);
                        _instance = singletonObject.AddComponent<T>();
                        DontDestroyOnLoad(singletonObject);
                    }
                }

                return _instance;
            }
        }
    }

    protected virtual void OnDestroy()
    {
        _applicationIsQuitting = true;
    }
}
public class GameManager : MonoSingleton<GameManager>
{
    public int score = 0;

    public void AddScore(int amount)
    {
        score += amount;
        Debug.Log("점수: " + score);
    }

    protected override void OnDestroy()
    {
        base.OnDestroy();
        Debug.Log("GameManager가 종료됩니다.");
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions