unity 单例类源码
时间: 2023-09-03 15:09:28 浏览: 111
unity水果连连看手游完整源码.zip
5星 · 资源好评率100%
以下是Unity中常见的单例类的源码示例:
1. GameManager单例类:
```csharp
public class GameManager : MonoBehaviour
{
private static GameManager _instance;
public static GameManager Instance
{
get
{
if (_instance == null)
{
_instance = FindObjectOfType<GameManager>();
if (_instance == null)
{
GameObject go = new GameObject();
go.name = "GameManager";
_instance = go.AddComponent<GameManager>();
}
}
return _instance;
}
}
//其他方法和变量
}
```
2. AudioManager单例类:
```csharp
public class AudioManager : MonoBehaviour
{
private static AudioManager _instance;
public static AudioManager Instance
{
get
{
if (_instance == null)
{
_instance = FindObjectOfType<AudioManager>();
if (_instance == null)
{
GameObject go = new GameObject();
go.name = "AudioManager";
_instance = go.AddComponent<AudioManager>();
}
}
return _instance;
}
}
//其他方法和变量
}
```
3. UIManager单例类:
```csharp
public class UIManager : MonoBehaviour
{
private static UIManager _instance;
public static UIManager Instance
{
get
{
if (_instance == null)
{
_instance = FindObjectOfType<UIManager>();
if (_instance == null)
{
GameObject go = new GameObject();
go.name = "UIManager";
_instance = go.AddComponent<UIManager>();
}
}
return _instance;
}
}
//其他方法和变量
}
```
以上示例代码中,单例类的实现方式基本相同,都是通过静态变量和静态方法来实现,使用时只需要调用类的静态方法Instance即可获取单例对象。如果当前场景中没有单例对象,则会自动创建一个新的GameObject,并将该单例脚本添加到该GameObject上。
阅读全文