http://www.u3dchina.com/t-6355-1-1.html
unity 中的 有一种类型 叫委托类型 今天在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");
-
}
-
}
-
}
-