2013년 11월 21일 목요일

Unity_ Generic Singletone 사용법


*.아래글에 코드가 잘안보여서 다시올립니다 ^^;

Generic Singleton 사용법에 대해서는 수많은.. 정말 무수히 많은 방법론이 존재하지만 제가생각하기에 Unity상에서 사용하기 괜찮은(좋은방법있으면 알려주시길 ㅠㅠ) 코드이다.

Singleton.cs
using UnityEngine;
using System.Collections;

public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
    protected static T sInstance;

    public static T GetInstance
    {
        get
        {
            if (sInstance == null)
            {
                sInstance = (T)FindObjectOfType(typeof(T));
            }

            if (sInstance == null)
            {
                Create();
            }

            return sInstance;
        }
    }

    private static void Create()
    {
        if (GameObject.Find("_Singleton"))
        {
            GameObject goInst = GameObject.Find("_Singleton");
            sInstance = goInst.AddComponent<T>();
        }
        else
        {
            GameObject goInst = new GameObject("_Singleton");
            sInstance = goInst.AddComponent<T>();
        }
    }
}


how to used
public class SettingManager : Singleton<Settingmanager> {

    private void OnApplicationQuit() {
        sInstance = null;
    }
}


싱글톤의 가장 기본적인 구조이고 이를 응용하여 생산성을 높이는 방법은 끝도없이 존재한다는 ^^




Categories: ,

0 개의 댓글:

댓글 쓰기