Unity engine

01_05_유니티 기초_Singleton 패턴

devRiripong 2022. 8. 25. 15:30
반응형

Q1. Managers를 싱글톤으로 구현하고 Player 오브젝트에서 사용할 수 있게 만들어 보자. @Managers 오브젝트가 없다면 코드로 생성하고 Managers 스크립트를 붙여지게 만들어 보자.

 

Managers.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Managers : MonoBehaviour
{
    static Managers s_instance; // 유일성이 보장된다. 
    public static Managers Instance { get { Init();  return s_instance; } }  // 유일한 매니저를 갖고온다. 

    // Start is called before the first frame update
    void Start()
    {
        Init(); 
    }

    // Update is called once per frame
    void Update()
    {
        
    }

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

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

Player.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        Managers mg = Managers.Instance;
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

궁금한 점 해결

go = new GameObject { name = "@Managers" };

에서 {}를 쓴 이유는 non static value의 초기화에는 {}를 이용해야 하기 때문이다. 

반응형