unity中C#委托的应用
在Unity开发中,委托类型是一种非常重要的类型。我们常常会将委托和事件放在一起讨论,实际上它们存在一些区别。委托(delegate)是一种类型,而事件(Event)是委托的一种实例。
下面通过一段代码来详细说明委托的使用:
using UnityEngine;
using System.Collections;
public class TestDelegate : MonoBehaviour
{
// 定义一个委托(其格式与类有些相似),用于指向某个函数,类似于C++里的指针函数
// param参数是名字
private delegate void DebugString(string param);
/// <summary>
/// 输出中文名字
/// </summary>
public void DebugNameOfChina(string str)
{
Debug.Log("中文名字:" + str);
}
/// <summary>
/// 输出英文名字
/// </summary>
public void DebugNameOfEnglish(string str)
{
Debug.Log("English Name:" + str);
}
// 定义一个委托的变量事件
private DebugString handlerDebugString;
void OnGUI()
{
if (GUILayout.Button("输出中文名字"))
{
// 若想输出中文名字,就将handlerDebugString赋值为输出中文名字的函数DebugNameOfChina
handlerDebugString = DebugNameOfChina;
handlerDebugString("丁小未");
}
else if (GUILayout.Button("Debug English Name"))
{
// 若想输出英文名字,就将handlerDebugString赋值为输出英文名字的函数DebugNameOfEnglish
handlerDebugString = DebugNameOfEnglish;
handlerDebugString("DingXiaowei");
}
}
}
在上述代码中,我们首先定义了一个委托类型DebugString,它可以指向一个接受string类型参数且返回值为void的函数。然后,我们实现了两个具体的函数DebugNameOfChina和DebugNameOfEnglish,分别用于输出中文名字和英文名字。接着,我们声明了一个DebugString类型的委托变量handlerDebugString。在OnGUI方法中,根据用户点击的按钮不同,将handlerDebugString赋值为不同的函数,从而实现不同的功能。
通过这种方式,委托为我们提供了一种灵活的机制,使得我们可以在运行时动态地指定要调用的函数,增强了代码的可扩展性和可维护性。