Unity 脚本单例类实现方法 - C# 代码示例
在 Unity 中,可以使用以下方式来创建一个脚本的单例类:
using UnityEngine;
public class Singleton : MonoBehaviour
{
private static Singleton instance;
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = FindObjectOfType<Singleton>();
if (instance == null)
{
GameObject singletonObject = new GameObject();
instance = singletonObject.AddComponent<Singleton>();
singletonObject.name = 'Singleton';
DontDestroyOnLoad(singletonObject);
}
}
return instance;
}
}
private void Awake()
{
if (instance == null)
{
instance = this;
DontDestroyOnLoad(this);
}
else
{
Destroy(gameObject);
}
}
// 在这里定义其他脚本的方法和属性
// 例如:
public void DoSomething()
{
Debug.Log('Doing something...');
}
}
在上面的例子中,Singleton 类继承自 MonoBehaviour,通过 Instance 属性来获取单例实例。在 Awake 方法中,如果实例不存在,则将当前脚本对象设置为实例,并使用 DontDestroyOnLoad 方法来保持该对象在场景切换时不被销毁。如果实例已经存在,则销毁当前脚本对象。然后,在类中可以定义其他的方法和属性来实现具体的功能。
使用时只需要通过 Singleton.Instance 来获取单例实例,并调用相应的方法即可,例如:Singleton.Instance.DoSomething()。
原文地址: http://www.cveoy.top/t/topic/nMP 著作权归作者所有。请勿转载和采集!