第一种懒汉式单例模式也叫静态方法访问:
public class MySingleton : MonoBehaviour
{
private static MySingleton instance;
// 私有构造函数
private MySingleton() { }
// 静态访问方法
public static MySingleton GetInstance()
{
if (instance == null)
{
instance = new GameObject("MySingleton").AddComponent<MySingleton>();
}
return instance;
}
// 可选:添加其他功能和数据到这个单例类
}
这种方式的优点是延迟初始化,即在第一次调用 GetInstance()
时创建实例。然而,这种方式在多线程环境下是非线程安全的。如果你需要在多线程环境中使用 MySingleton,可以使用 lock
关键字来确保线程安全。
第二种unity特有的单例模式也叫静态字段访问
public class GameManager : MonoBehaviour
{
public static GameManager instance;
private void Awake()
{
if(instance != null)
{
Destroy(gameObject);
}
else
{
instance = this;
DontDestroyOnLoad(gameObject);
}
}
public void Walk()
{
// 实现 Walk 方法的代码
}
}
这种方式的优点是线程安全,并且在 Unity 环境中非常实用,因为它利用了 Unity 的生命周期管理。然而,这种实现方式依赖于 Unity 引擎,无法在非 Unity 环境中使用。