Unity单例模式技术
时间: 2023-06-13 16:08:48 浏览: 214
在Unity中,单例模式可以用于确保在整个游戏中只有一个实例被创建。以下是一种常见的Unity单例模式实现方法:
```csharp
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static T instance;
public static T Instance
{
get
{
if (instance == null)
{
instance = FindObjectOfType<T>();
if (instance == null)
{
GameObject obj = new GameObject();
obj.name = typeof(T).Name;
instance = obj.AddComponent<T>();
}
}
return instance;
}
}
protected virtual void Awake()
{
if (instance == null)
{
instance = this as T;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}
}
```
这个单例模式的实现方法使用了泛型以便适用于任何类型的单例。在 `Instance` 属性中,首先检查是否已经存在一个实例,如果没有就通过 `FindObjectOfType` 方法查找,如果仍然没有找到,就创建一个新的游戏对象并添加组件。 在 `Awake` 方法中,如果已经存在一个实例,就销毁当前游戏对象;否则,将当前实例设置为单例并保留在场景中。这样,在整个游戏中,我们可以通过 `Singleton<YourClassName>.Instance` 属性来访问单例对象。
阅读全文
相关推荐
















