Unity 유 니 버 설 범용 단일 디자인 모델(일반 형 과 계승 은 MonoBehaviour)

단일 모델 은 디자인 모델 에서 가장 흔히 볼 수 있 는 것 으로 설명 이 많 지 않다.그러나 가능 한 한 사용 을 피해 야 하 며,일반 전역 관리 류 는 하나의 예 를 사용 해 야 한다.
일반 일반적인 예:

public abstract class Singleton<T> where T : class, new()
{
  private static T instance = null;

  private static readonly object locker = new object();

  public static T Instance
  {
    get
    {
      lock (locker)
      {
        if (instance == null)
          instance = new T();
        return instance;
      }
    }
  }
}
MonoBehaviour 의 일반적인 예 를 계승 합 니 다.

using UnityEngine;

public abstract class MonoSingleton <T>: MonoBehaviour where T:MonoBehaviour
{
  private static T instance = null;

  private static readonly object locker = new object();

  private static bool bAppQuitting;

  public static T Instance
  {
    get
    {
      if (bAppQuitting)
      {
        instance = null;
        return instance;
      }

      lock (locker)
      {
        if (instance == null)
        {
          instance = FindObjectOfType<T>();
          if (FindObjectsOfType<T>().Length > 1)
          {
            Debug.LogError("         !");
            return instance;
          }

          if (instance == null)
          {
            var singleton = new GameObject();
            instance = singleton.AddComponent<T>();
            singleton.name = "(singleton)" + typeof(T);
            singleton.hideFlags = HideFlags.None;
            DontDestroyOnLoad(singleton);
          }
          else
            DontDestroyOnLoad(instance.gameObject);
        }
        instance.hideFlags = HideFlags.None;
        return instance;
      }
    }
  }

  private void Awake()
  {
    bAppQuitting = false;
  }

  private void OnDestroy()
  {
    bAppQuitting = true;
  }
}
사용 방법 은 이 두 추상 적 인 사례 를 클래스 로 직접 계승 하면 됩 니 다.T.Instance 를 사용 하면 이 클래스(T)의 유일한 인 스 턴 스 를 직접 얻 을 수 있 습 니 다.
이상 은 유 니 티 유 니 버 설 디자인 모델(일반 형 과 모 노 Behaviour 계승)의 상세 한 내용 입 니 다.유 니 티 단일 디자인 모델 에 관 한 자 료 는 저희 의 다른 관련 글 을 주목 해 주 십시오!

좋은 웹페이지 즐겨찾기