unity单例模式的例子
时间: 2023-08-13 18:26:48 浏览: 113
在Unity中,使用单例模式是一种常见的设计模式,用于确保某些对象在整个应用程序中具有唯一性。下面是一个简单的Unity单例模式的例子:
```csharp
using UnityEngine;
public class GameManager : MonoBehaviour
{
private static GameManager instance;
private void Awake()
{
if (instance == null)
{
instance = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}
public static GameManager GetInstance()
{
return instance;
}
public void StartGame()
{
// 开始游戏逻辑
}
public void EndGame()
{
// 结束游戏逻辑
}
}
```
在上面的代码中,GameManager类是一个单例类。在Awake函数中,我们将GameManager的实例分配给静态变量instance,并使用DontDestroyOnLoad函数保持其唯一性。如果已经存在GameManager实例,则销毁新的实例,以确保只有一个实例存在于游戏中。
GetInstance函数是一个静态函数,用于获取GameManager的实例。可以通过以下代码来访问GameManager实例:
```csharp
GameManager gameManager = GameManager.GetInstance();
```
StartGame和EndGame函数是示例游戏逻辑,可以根据具体需求进行修改。
通过上面的代码,我们可以在整个应用程序中使用GameManager实例,并确保其唯一性。
阅读全文
相关推荐


















