[Unity] 매니저 생성, MonoBehaviour

Jihoon·2022년 3월 8일
0

MMO_Unity

목록 보기
1/22

이 MMO_unity 프로젝트는 인프런의 MMORPG 게임 개발, 켠김에 끝판왕까지! (유니티 + C#) 강의를 보고 작성하였습니다. (https://www.inflearn.com/roadmaps/355)

MonoBehaviour

MonoBehaviour는 유니티에서 사용되는 C# 클래스들이 상속받는 클래스이다.
C# 스크립트들이 유니티의 컴포넌트로서 작동될 수 있게 한다.

매니저 생성

MonoBehaviour를 상속받은 클래스는 new를 통해서 인스턴스화 될 수 없다.
따라서 클래스를 인스턴스화 하기 위해 아무 기능을 하지 않는 GameObject를 생성하고
인스턴스화 하고싶은 클래스를 컴포넌트로 넣어서 인스턴스화 하게 된다.

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

이렇듯 매니저를 Static을 통해 한개의 객체만 생성해서(한번의 인스턴스화) 코드를 관리하는 것을 싱글톤 패턴이라고 한다.

profile
클라이언트 개발자 지망생

0개의 댓글

관련 채용 정보

Powered by GraphCDN, the GraphQL CDN