본문 바로가기
Unity/3d MMORPG

[Unity] Managers

by 후야- 2024. 3. 30.

1. GameObject 로 Managers 찾아오기

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

public class Player : MonoBehaviour
{  
    void Start()
    {
        GameObject go = GameObject.Find("@Managers");
        Managers mg = go.GetComponent<Managers>();
        
    }
 
    void Update()
    {
        
    }
}

→ 게임 오브젝트를 이름으로 찾는거는 별로 좋지 않다. (부하가 굉장히 심함)

 

 

2. Managers 만들고 Player 연동하기

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

public class Managers : MonoBehaviour
{
    // property 
    // 싱글톤 : 특정 클래스에 인스턴스가 한 개만 있길 원할 때 사용함 > @Managers 가 하나밖에 없음
    static Managers s_instance;  // 유일성이 보장됨
    public static Managers Instance { get { Init(); return s_instance; } }  // 유일한 매니저를 갖고온다.

    void Start()
    {
        Init();
    }


    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>();                 // Managers 스크립트 붙여주기
            }

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

}

 

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

public class Player : MonoBehaviour
{

    void Start()
    {        
        Managers mg = Managers.Instance;
        
    }
   
    void Update()
    {
        
    }
}