기타 기술/C#

Singleton pattern

hawon6691 2023. 8. 12. 16:27
728x90
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test : MonoBehaviour
{
    static Test s_instance;
    static public Test Instance { get { Init(); return s_instance; } }

    private void Start()
    {
        Init();
    }

    static void Init()
    {
        if(s_instance == null)
        {
            GameObject go = GameObject.Find("ObjectName");
            if(go == null)
            {
                go = new GameObject { name = "ObjectName" };
                go.AddComponent<Test>();
            }

            DontDestroyOnLoad(go);
            s_instance = go.GetComponent<Test>();
        }
    }
}

 

사용

 

Test test = Test.Instance;
728x90

'기타 기술 > C#' 카테고리의 다른 글

NavMeshAgent 기본값  (0) 2023.08.19
ResourceManager  (0) 2023.08.12
NavMeshAgent  (0) 2023.08.11
이진 트리로 미로 생성  (0) 2023.08.11
ObjectPool Dictionary  (0) 2023.08.02