内容: |
警告
这篇文章是相当过时和缺少一点的解释。一起阅读Singleton.
描述
下面的代码段演示如何添加一个名为 instance,将自动在scene 找到的类的实例并返回它的静态属性。
这是有用的managers 和其他行为,在场景中仅有一个实例 和需要从其他类访问,因为它避免了每个类保持对管理器对象的引用。
提示:把游戏managers 在场景的hierarchy 中的好地方是创建一个空的游戏对象,所谓的Managers 并附加到它上面的所有manager 行为。
使用
使用代码示例作为模板,当创建一个manager类型的脚本。记住要用您的类的名称替换所有的AManager 。若要访问一个函数,你调用它与manager 中的 foo () (在"AManager"再次应替换您的类的名称):
AManager.instance.Foo();
C# - AManager.cs
/// Contribution Create Missing Instance 10/2010: Daniel P. Rossi (DR9885)
using UnityEngine;
using System.Collections;
/// AManager is a singleton.
/// To avoid having to manually link an instance to every class that needs it, it has a static property called
/// instance, so other objects that need to access it can just call:
/// AManager.instance.DoSomeThing();
///
public class AManager : MonoBehaviour {
// s_Instance is used to cache the instance found in the scene so we don't have to look it up every time.
private static AManager s_Instance = null;
// This defines a static instance property that attempts to find the manager object in the scene and
// returns it to the caller.
public static AManager instance {
get {
if (s_Instance == null) {
// This is where the magic happens.
// FindObjectOfType(...) returns the first AManager object in the scene.
s_Instance = FindObjectOfType(typeof (AManager)) as AManager;
}
// If it is still null, create a new instance
if (s_Instance == null) {
GameObject obj = new GameObject("AManager");
s_Instance = obj.AddComponent(typeof (AManager)) as AManager;
Debug.Log ("Could not locate an AManager object. \ AManager was Generated Automaticly.");
}
return s_Instance;
}
}
// Ensure that the instance is destroyed when the game is stopped in the editor.
void OnApplicationQuit() {
s_Instance = null;
}
// Add the rest of the code here...
public void DoSomeThing() {
Debug.Log("Doing something now", this);
}
}