본문 바로가기

게임프로그래밍

[MMO Lab 1기] 싱글톤(Singleton)

** 싱글톤 : 딱 하나만 객체가 존재
   ㄴ 매니저를 구현할 때, 싱글톤으로 구현한다
   ㄴ  static 변수를 이용한다

=> static은 클래스에 종속적이다고 표현 가능

 

using UnityEngine;

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

    public 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>();
        }
    }

    public void PlaySound()
    {
        Debug.Log("PlaySound");
    }

    public void ShowUI()
    {
        Debug.Log("ShowUI");
    }
}

 

using UnityEngine;

public class Player : MonoBehaviour
{

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

    // Update is called once per frame
    void Update()
    {
        Managers.Instance.PlaySound();
    }
}