
클래스 정의
public class Singleton<T> : MonoBehaviour where T : Component
Singleton 클래스는 T 라는 제네릭 타입을 받아들이며, 이 타입은 Component를 상속받아야 한다.T 는 Unity의 MonoBehaviour를 상속받는 모든 클래스가 될 수 있다.정적 인스턴스 변수
private static T _instance;
T 타입의 싱글톤 인스턴스를 저장하는 정적 변수로, 내 모든 인스턴스가 이 변수를 공유한다.Instance 프로퍼티
public static T Instance
{
get
{
if (_instance == null)
{
_instance = FindObjectOfType<T>();
if(_instance == null)
{
GameObject obj = new GameObject();
obj.name = typeof(T).Name;
_instance = obj.AddComponent<T>();
}
}
return _instance;
}
}
Instance 프로퍼티는 싱글톤 인스턴스를 반환하고 인스턴스가 아직 생성되지 않았다며느 새로운 인스턴스를 생성하고 반환한다.FindObjectOfType<T>()를 사용해 씬에서 T 타입의 오브젝트를 찾고 , 없을 경우 새로운 GameObject를 생성하여 T 타입의 컴포넌트를 추가한다.Awake 메서드
public void Awake()
{
if( _instance == null )
{
_instance = this as T;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}
Awake 메서드는 인스턴스가 처음 생성될때 호출.DonDestroyOnLoad를 호출한다.public class Singleton<T> : MonoBehaviour where T : Component
{
private static T _instance;
public static T Instance
{
get
{
if (_instance == null)
{
_instance = FindObjectOfType<T>();
if(_instance == null)
{
GameObject obj = new GameObject();
obj.name = typeof(T).Name;
_instance = obj.AddComponent<T>();
}
}
return _instance;
}
}
public void Awake()
{
if( _instance == null )
{
_instance = this as T;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}
}
DontDestroyOnLoad 를 통해 씬 전환이 일어나도 인스턴스를 유지한다.GameManager라는 클래스를 싱글톤으로 만들고 싶을때public class GameManager : Singleton<GameManager>
{
// GameManager의 내용
}
GameManager.Instance를 통해 어디서든지 GameManager 인스턴스에 접근이 가능하다.