using UnityEngine;
/// <summary>
/// 이 싱글톤 클래스는 싱글톤으로 되길 원하는 스크립트에 상속만 하면 되는 스크립트입니다
/// </summary>
/// <typeparam name="T"> MonoBehaviour을 상속받는 스크립트 이름 </typeparam>
[DisallowMultipleComponent] // Unity 어트리뷰트로, 해당 스크립트가 동일한 게임 오브젝트에 여러 번 추가되는 것을 방지합니다
public abstract class SingleTon<T> : MonoBehaviour where T : MonoBehaviour
{
private static T m_instance;
private static bool m_isApplicationQuit = false;
public static T Instance
{
get
{
if ( true == m_isApplicationQuit)
return null;
// 씬에 있는 스크립트를 찾습니다
if ( null == m_instance)
{
T[] _finds = FindObjectsOfType<T>();
if( _finds.Length > 0)
{
m_instance = _finds[0];
DontDestroyOnLoad(m_instance.gameObject);
}
if(_finds.Length > 1)
{
for( int i=1; i<_finds.Length; i++)
{
Destroy(_finds[i].gameObject);
}
Debug.LogError("There is more than one" + typeof(T).Name + " in the Scene.");
}
}
// 씬에 있는 스크립트가 없을 경우 그 스크립트가 부착된 게임오브젝트를 생성하여 줍니다.
if ( null == m_instance)
{
GameObject _createGameObject = new GameObject(typeof(T).Name);
DontDestroyOnLoad(_createGameObject);
m_instance = _createGameObject.AddComponent<T>();
}
return m_instance;
}
}
private void OnApplicationQuit()
{
m_isApplicationQuit = true;
}
}
위의 싱글톤 스크립트를 생성한 후
싱글톤이 되길 원하는 스크립트에 상속만 시키면 됩니다
ex) GameManager.cs
using UnityEngine;
public class GameManager : SingleTon<GameManager>
{
// 각종 GameManager 안의 코드들.. 생략
}