본문 바로가기

Unity

[Unity] Generic Singleton 사용하기

싱글톤은 단 하나의 인스턴스만 생성할 수 있도록 하며,  unity의 경우 특정 오브젝트에 컴포넌트로 붙이지 않아도 어디에서나 사용할수있다는 장점이 있다. 주로 매니저클래스나 컨트롤러 클래스를 싱글톤으로 만들어 관리한다.

 

싱글톤 패턴은 다양한데, 나는 제네릭을 사용하여 구현하였다.

 

 

 

>>Singleton.cs

using System;
using System.Reflection;


namespace UnityEngine
{
    public partial class GameFramework : MonoBehaviour
    {
        public class Singleton<T> where T : class, new()
        {
            public Singleton() { }
            ~Singleton() { }

            public static T
            GetInstance()
            {
                if (_instance == null)
                {
                    _instance = new T();
                }

                return _instance;
            }

            public void
            Relese()
            {
                if (null != _instance)
                {
                    _instance = null;
                }
            }

            private static T _instance = null;
        }
    }
}

위의 'public partial class GameFramework : Monobehaviour 는 내가 따로 만들어 사용한 프레임워크라서 넣어준것이다. 

 

 

싱글톤패턴을 사용하는 방법은 다음과 같다.

public class Controller : Singleton<Contoller>{
	
	public string value = "something";
    
    //..do something
}