Unity3D 單例模式

CnctSoft發表於2019-05-11

using UnityEngine;

public class UnitySingleton<T>:MonoBehaviour where T:Component
{
	private static T _instance;

	public static T getInstance {
		get {
			if (_instance == null) {
				_instance = FindObjectOfType (typeof(T)) as T;
				if (_instance == null) {
					GameObject obj = new GameObject ();
					obj.hideFlags = HideFlags.HideAndDontSave;//隱藏例項化的new game object,	
				}
			}
			return _instance;

		}
	}

	public virtual void Awake ()
	{
		DontDestroyOnLoad (this.gameObject);
		if (_instance == null) {
			_instance = this as T;
		} else {
			Destroy (gameObject);
		}
	}
}



內容均為作者獨立觀點,不代表八零IT人立場,如涉及侵權,請及時告知。

相關文章