关于Unity中委托与回调函数的应用

1.首先我们需要构造一个用于传输数据并承载回调函数的类

比如:(根据需要自定义构造)

 1 using UnityEngine;
 2 using System.Collections;
 3 
 4 //回调函数
 5 public delegate void WarningResult();
 6 public class WarningModel : MonoBehaviour
 7 {
 8     //回调函数
 9     public WarningResult result;
10     //警告文本
11     public string value;
12 
13     //构造警告结构体
14     public WarningModel(string s_value, WarningResult s_result = null)
15     {
16         this.value = s_value;
17         this.result = s_result;
18     }
19 }

2.然后在需要的时候实例化出来构造结构体

比如:

 1    /// <summary>
 2     /// 进入游戏按钮触发
 3     /// </summary>
 4     void OnLoginClick()
 5     {
 6         //验证账号密码
 7         //如果账号密码有误,则显示警告面板并return返回
 8         if (m_inputAccount.text == "" || m_inputPassWord.text == "")
 9         {
10                                                             //警告信息                  //回调函数
11             WarningManager.instance.AddWarringError("输入的账号密码不正确,请重新输入",Result);
12             return;
13         }
14 
15 
16         //进入游戏,按钮弃用
17         m_enterGameBtn.interactable = false;
18 
19         
20     }
21     //测试用回调函数
22     void Result()
23     {
24         Debug.Log("登录界面回调函数");
25     }
26     

3.最后在需要实现该函数的类中承接回调函数,并实现该方法

如下:

 1  //处理警告后的回调函数
 2     private WarningResult result;
 3 
 4     /// <summary>
 5     /// 供外部调用传递显示的警告信息方法
 6     /// </summary>
 7     /// <param name="s_warning">警告信息结构体</param>
 8     public void DoShowWarring(WarningModel s_warning)
 9     {
10         //激活警告界面
11         gameObject.SetActive(true);
12 
13         //如果游戏物体没来的及找到,则先赋值游戏物体
14         if (m_warningTex == null)
15         {
16             Init();
17         }
18 
19         //显示警告信息
20         m_warningTex.text = s_warning.value;
21         //填充回调函数
22         this.result = s_warning.result;
23 
24         //如果回调函数不为空,则执行回调函数
25         if (result != null)
26         {
27             result();
28         }
29     }
原文地址:https://www.cnblogs.com/mrmocha/p/8016599.html