Unity Singleton

 https://debuglog.tistory.com/35


Singleton.cs

using UnityEngine;

public abstract class Singleton<T> where T : class {

    protected static T instance = null;
    public static T Instance
    {
        get
        {
            if (instance == null)
            {
                instance = System.Activator.CreateInstance (typeof(T)) as T;
            }
            return instance;
        }
    }
}


MonoSingleton.cs

using UnityEngine; public class MonoSingleton<T> : MonoBehaviour where T : MonoBehaviour { protected static T instance = null; public static T Instance { get { instance = FindObjectOfType (typeof(T)) as T; if (instance == null) { instance = new GameObject ("@"+typeof(T).ToString (),                                           typeof(T)).AddComponent<T>(); DontDestroyOnLoad (instance); } return instance; } } }

Generic Singleton클래스와 MonoSingleton 클래스이다.

생성부분에서 차이가 있음.



GameManager.cs

using UnityEngine;

public class GameManager : Singleton<GameManager> {
    public void Call(){
        Debug.Log ("GameManager Call()");
    }
}


SoundManager.cs

using UnityEngine;

public class SoundManager : MonoSingleton<SoundManager> {

    public void Call(){
        Debug.Log ("SoundManager Call()");
    }
}

각각 Singleton과 MonoSingleton을 상속받았다.



SingletonTest.cs

using UnityEngine;

public class SingletonTest : MonoBehaviour {
    
    void Start () {
        GameManager.Instance.Call ();
        SoundManager.Instance.Call ();
    }
}

테스트.

댓글

이 블로그의 인기 게시물

About AActor!!! "UObject" has no member "BeginPlay"

UNREAL Android build information

C++ 생성자 위임 (delegating constructor)