HOIT_B

[ 디자인패턴 ] Singleton 본문

유니티

[ 디자인패턴 ] Singleton

HOIT_77 2024. 3. 6. 15:52
728x90

싱글톤은 한개의 클래스 인스턴스만을 가지도록 보장하고, 이에 대한 전역적인 접근을 제공하는 디자인패턴이다.

 

예를들어 Player스크립트에서 @Manager객체의 manager스크립트에 접근하기 위해서 아래같은 코드를 사용할 수 있다.

        GameObject go = GameObject.Find("@Manager");
        Manager mg = go.GetComponent<Manager>();

하지만 게임 오브젝트를 이름으로 찾는것은 부하가 심하기 때문에 자주 사용하는 것을 지양해야한다. 

 

아래는 싱글톤을 구현한 코드들이다. 

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

public class Manager : MonoBehaviour
{
	
    public static Manager Instance; //staic특성으로 유일성 보장
    public static Manager GetInstace()
    {
        Init();
        return Instance;
    } 


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

    }

    static void Init()
    {
        if (Instance == null)
        {
            GameObject go = GameObject.Find("@Manager"); //객체가 있는지 체크
            if (go == null) //해당 객체가 없다면 
            {
                //새로 만들어준다.
                go = new GameObject
                {
                    name = "@Manager" 
                };
                
                DontDestroyOnLoad(go);
                //스크립트를 붙여준다.
                Instance = go.AddComponent<Manager>();
            }
            

        }

    }
}

인프런 강의에서 강사님이 구현한 코드이다. 

 

나는 보통 아래처럼 구현한다. 

private static DataManager _instance;

    public static DataManager Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = GameObject.Find("DataManager").GetComponent<DataManager>();
            }
            return _instance;
        }
    }
    private void Awake()
    {
        if (_instance == null)
        {
            _instance = this;
        }
        else
        {
            Destroy(this.gameObject);
        }
    }

 

참고 

인프런 [C#과 유니티로 만드는 MMORPG 게임 개발 시리즈] Part3: 유니티 엔진 

학교 다닐 때 받은 강의를 이제 본다..! 그때 본것같았는데 놀랍게도 진행률 10%였다.

728x90
Comments