【发布时间】:2018-03-08 21:50:21
【问题描述】:
我是 Unity 的初学者。
我目前正在实施单例。
我在学习时有问题。
像标题一样在 Unity 中实现 Singleton 的最佳方法是什么?
我明白为什么要使用单例。那是.. " 一次创建一个对象,并在需要时使用它。"
我理解正确吗?
有很多方法可以实现单例。这是正确的? 那么,众多方法中哪一部分是共同使用的呢?
我的单例代码是:
public class GameSingleton<T> : MonoBehaviour where T : MonoBehaviour
{
protected static T instance = null;
protected virtual void Awake()
{
Debug.Log ("instance was !!!!! >>" + instance);
if(instance != null) // 최초 instance 유효성 검사
{
Debug.Log(">> Game Singleton already exist!");
return;
}
instance = FindObjectOfType<T>(); //
Debug.Log("FindObj" + "/" + "instance is >> " + instance);
}
// Use this for initialization
protected virtual void Start()
{
}
// Update is called once per frame
protected virtual void Update()
{
}
protected virtual void OnDestroy()
{
if (instance != null)
{
instance = null;
}
}
public static T Instance
{
get
{
if(instance == null)
{
GameObject go = new GameObject();
go.transform.position = Vector3.zero; // Vector3(0,0,0)
go.transform.rotation = Quaternion.identity; // 회전 없음
go.transform.localScale = Vector3.one;
go.hideFlags = HideFlags.HideAndDontSave;
instance = go.AddComponent<T>();
instance.name = (typeof(T)).ToString();
Debug.Log(">> Game Singleton instance create : " + instance);
}
return instance;
}
}
}
如果您能查看代码,我们将不胜感激, 但我们也很欣赏一些关键点。
我看过几个文件,但它们只会变得复杂。 我的水平很低。如果您能简单地解释一下,我将不胜感激。
【问题讨论】: