이 MMO_unity 프로젝트는 인프런의 MMORPG 게임 개발, 켠김에 끝판왕까지! (유니티 + C#) 강의를 보고 작성하였습니다. (https://www.inflearn.com/roadmaps/355)
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을 통해 한개의 객체만 생성해서(한번의 인스턴스화) 코드를 관리하는 것을 싱글톤 패턴이라고 한다.