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 계승)의 상세 한 내용 입 니 다.유 니 티 단일 디자인 모델 에 관 한 자 료 는 저희 의 다른 관련 글 을 주목 해 주 십시오!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
TypeScript 를 VsCode 로 편집 합 니 다.json 을 통 해 정의 되 었 습 니 다.이 파일 은 ts 프로젝트 루트 디 렉 터 리 를 지정 하고 프로젝트 에 속 하 는 파일 과 컴 파일 옵션 을 보 여 줍 니 다.tsconfig. vscode 는 작업 실행...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.