본문 바로가기
개발더미

[개발더미][Unity] 모노 싱글톤

by 스테디코디스트 2023. 7. 25.
반응형
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
    private static object lockObject = new object(); // 쓰레드 안전화에 사용
    private static bool isQuit = false; // 프로그램이 종료되거나 이상이 있는 경우 판단
    private static T instance = null; // 객체

    public static T Instance
    {
        // 쓰레드 안전화(Thread-Safe)
        get
        {           
            // lock블럭 : 한번에 한 쓰레드만 실행되도록 함
            lock (lockObject)
            {
                // 씬에 없거나 비활성화 되어있는 경우 -> 새로 생성
                if (isQuit) 
                {
                    Debug.LogWarning("싱글톤 객체가 없어서 새로 생성합니다.");
                    return null;
                }

                // instance가 NULL일 때 새로 생성
                if (instance == null)
                {
                    // 존재하는 객체를 찾음
                    instance = (T)FindObjectOfType(typeof(T));

                    if (instance == null)
                    {
                        // 그래도 없는 경우
                        var singletonObject = new GameObject();
                        instance = singletonObject.AddComponent<T>();
                        singletonObject.name = typeof(T).ToString() + " (Singleton)";

                        // 씬이 바뀌어도 사라지지 않게함
                        DontDestroyOnLoad(singletonObject);
                    }
                }

                return instance;
            }
        }
    }

    public void OnApplicationQuit()
    {
        isQuit = true;
    }

    private void OnDestroy()
    {
        isQuit = true;
    }
}