使用时继承该单例类,不用管什么多线程之类的问题,也不用担心性能问题,因为在最开始的时候不管你要不要这个实例,都会被创建出来,所以只是在程序开始的时候消耗时间,到程序结束前不会销毁。
第一个是不继承MonoBehaviour
public class SingletonNull<T> where T : new()
{
private static T m_instance;
public static T Instance
{
get
{
if (m_instance == null)
{
m_instance = new T();
}
return m_instance;
}
}
}
第二个是继承MonoBehaviour
using UnityEngine;
public class SingletonMono<T> : MonoBehaviour where T : SingletonMono<T>
{
public bool Global = true;
private static T m_instance = default;
public static T Instance {
get
{
if (m_instance == null)
{
m_instance = FindObjectOfType<T>();
}
return m_instance;
}
}
private void Awake()
{
if (Global)
{
if (m_instance != null && m_instance != this.gameObject.GetComponent<T>())
{
Destroy(this.gameObject);
return;
}
DontDestroyOnLoad(this.gameObject);
m_instance = this.gameObject.GetComponent<T>();
}
this.OnStart();
}
protected virtual void OnStart() { }
}
本文介绍了如何在Unity3D中利用C#实现单例模式,特别是当继承MonoBehaviour时的处理。这种方法确保了在游戏运行过程中只有一个实例存在,解决了多线程和性能问题。虽然初始化时会消耗一定时间,但实例在整个程序生命周期内保持活跃。

3682

被折叠的 条评论
为什么被折叠?



