using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SingletonMonobehaviour<T> : MonoBehaviour where T : MonoBehaviour
{
static T _Instance = null;
public static T Instance
{
get
{
if (_Instance == null)
{
//_Instance가 Null일 경우 찾아본다.
_Instance = (T)FindObjectOfType(typeof(T));
if (_Instance == null)
{
var _NewGameObject = new GameObject(typeof(T).ToString());
_Instance = _NewGameObject.AddComponent<T>();
}
}
return _Instance;
}
}
protected virtual void Awake()
{
if (_Instance == null)
{
_Instance = this as T;
}
DontDestroyOnLoad(gameObject);
}
}
// Singleton 상속
public class TestApp : SingletonMonobehaviour<TestApp>
{
protected override void Awake()
{
base.Awake();
}
public void TestFunction()
{
}
}
public class TestSingleton : MonoBehaviour
{
private void Awake()
{
TestApp.Instance.TestFunction();
}
}
클래스의 인스턴스를 반환하는 공용 정적 속성
인스턴스가 null이면 장면에서 클래스의 기존 인스턴스를 검색
인스턴스를 찾을 수 없으면 새 인스턴스를 생성
if (_Instance == null)
{
//_Instance가 Null일 경우 찾아본다.
_Instance = (T)FindObjectOfType(typeof(T));
if (_Instance == null)
{
var _NewGameObject = new GameObject(typeof(T).ToString());
_Instance = _NewGameObject.AddComponent<T>();
}
}
return _Instance;
인스턴스가 장면에 하나만 존재하도록 하는 편리한 방법으로
게임 상태, 컨트롤러 또는 여러 인스턴스를 가져서는 안 되는 기타 구성 요소를 관리하는 데 유용



