码迷,mamicode.com
首页 > 编程语言 > 详细

unity泛型单例

时间:2015-03-06 23:40:48      阅读:516      评论:0      收藏:0      [点我收藏+]

标签:

参考自:http://wiki.unity3d.com/index.php/Singleton

我们要使用Unity3d在Object类中提供了一个静态函数 :Object.DontDestroyOnLoad (Object target) . 加载新场景的时候使单例对象不被自动销毁

作为 MonoBehaviour 因为我们可能需要协同程序,所以使用 Lock同步

用法示例

MyClass.cs

public class MyClass : MonoBehaviour {
	void Awake () {
		Debug.Log(Manager.Instance.myGlobalVar);
	}
}

Manager.cs

public class Manager : Singleton<Manager> {
	protected Manager () {} // guarantee this will be always a singleton only - can‘t use the constructor!
 
	public string myGlobalVar = "whatever";
}

执行

Singleton.cs

using UnityEngine;
 
/// <summary>
/// Be aware this will not prevent a non singleton constructor
///   such as `T myT = new T();`
/// To prevent that, add `protected T () {}` to your singleton class.
/// 
/// As a note, this is made as MonoBehaviour because we need Coroutines.
/// </summary>
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
	private static T _instance;
 
	private static object _lock = new object();
 
	public static T Instance
	{
		get
		{
			if (applicationIsQuitting) {
				Debug.LogWarning("[Singleton] Instance ‘"+ typeof(T) +
					"‘ already destroyed on application quit." +
					" Won‘t create again - returning null.");
				return null;
			}
 
			lock(_lock)
			{
				if (_instance == null)
				{
					_instance = (T) FindObjectOfType(typeof(T));
 
					if ( FindObjectsOfType(typeof(T)).Length > 1 )
					{
						Debug.LogError("[Singleton] Something went really wrong " +
							" - there should never be more than 1 singleton!" +
							" Reopening the scene might fix it.");
						return _instance;
					}
 
					if (_instance == null)
					{
						GameObject singleton = new GameObject();
						_instance = singleton.AddComponent<T>();
						singleton.name = "(singleton) "+ typeof(T).ToString();
 
						DontDestroyOnLoad(singleton);
 
						Debug.Log("[Singleton] An instance of " + typeof(T) + 
							" is needed in the scene, so ‘" + singleton +
							"‘ was created with DontDestroyOnLoad.");
					} else {
						Debug.Log("[Singleton] Using instance already created: " +
							_instance.gameObject.name);
					}
				}
 
				return _instance;
			}
		}
	}
 
	private static bool applicationIsQuitting = false;
	/// <summary>
	/// When Unity quits, it destroys objects in a random order.
	/// In principle, a Singleton is only destroyed when application quits.
	/// If any script calls Instance after it have been destroyed, 
	///   it will create a buggy ghost object that will stay on the Editor scene
	///   even after stopping playing the Application. Really bad!
	/// So, this was made to be sure we‘re not creating that buggy ghost object.
	/// </summary>
	public void OnDestroy () {
		applicationIsQuitting = true;
	}
}

要求

(从GetOrAddComponent MonoBehaviourExtended.cs)

static public class MethodExtensionForMonoBehaviourTransform {
	/// <summary>
	/// Gets or add a component. Usage example:
	/// BoxCollider boxCollider = transform.GetOrAddComponent<BoxCollider>();
	/// </summary>
	static public T GetOrAddComponent<T> (this Component child) where T: Component {
		T result = child.GetComponent<T>();
		if (result == null) {
			result = child.gameObject.AddComponent<T>();
		}
		return result;
	}
}


??

unity泛型单例

标签:

原文地址:http://blog.csdn.net/u010019717/article/details/44106737

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!