关于Unity中单例调用和委托的使用方式

本文探讨了在Unity开发中,使用委托而非单例来处理GameObject操作的原因。通过一个具体的示例说明了两种方法在实际应用中的不同表现,并解释了为何在涉及GameObject时推荐使用委托。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在Unity中,通过单例调用的方法中如果包含已初始化的GameObject,则调用后为null而报错,这时应该使用委托的方式,举例:
public delegate void PanelDelegate(string column);
public static PanelDelegate panelShowNormal;
void Start () {
public GameObject Toast;
Toast.SetActive(false);
panelShowNormal += ShowToast;
}
public void ShowToast(string Column) {
Toast.SetActive(true);
Toast.transform.GetChild(0).gameObject.GetComponent().text = Localization.Get(Column);
}

上述代码,分别用下列两种方式调用:

PanelManager.panelShowNormal(“updateSuccess”); //调用成功,执行成功

SingleTon.Instance.ShowToast(“updateSuccess”); //调用成功,执行失败,Toast报null

结论:当涉及到有GameObject的时候,使用委托而不使用单例。

Unity中创建模式的调用方法通常有以下几种方式: 1. 静态属性:在类中定义一个静态属性,用于保存实化后的对象。在需要使用对象的地方,通过类名直接调用该属性即可。 ```csharp public class SingletonClass { private static SingletonClass instance; public static SingletonClass Instance { get { if (instance == null) { instance = new SingletonClass(); } return instance; } } } ``` 调用: ```csharp SingletonClass.Instance.SomeMethod(); ``` 2. 静态方法:在类中定义一个静态方法,用于返回对象。在需要使用对象的地方,通过类名调用该静态方法获取对象的实。 ```csharp public class SingletonClass { private static SingletonClass instance; public static SingletonClass GetInstance() { if (instance == null) { instance = new SingletonClass(); } return instance; } } ``` 调用: ```csharp SingletonClass.GetInstance().SomeMethod(); ``` 3. MonoBehaviour方式:在继承自MonoBehaviour的类中使用Awake()方法来实现模式。在需要使用对象的地方,通过类名调用该类的静态属性即可。 ```csharp public class SingletonClass : MonoBehaviour { private static SingletonClass instance; public static SingletonClass Instance { get { if (instance == null) { instance = FindObjectOfType<SingletonClass>(); if (instance == null) { GameObject singletonObject = new GameObject(); instance = singletonObject.AddComponent<SingletonClass>(); DontDestroyOnLoad(singletonObject); } } return instance; } } private void Awake() { if (instance == null) { instance = this; DontDestroyOnLoad(gameObject); } else { Destroy(gameObject); } } } ``` 调用: ```csharp SingletonClass.Instance.SomeMethod(); ``` 这些是一些常见的在Unity中实现模式的调用方法,你可以根据自己的需求选择适合的方式使用
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值