Unity中使用反射机制调用函数
2021-03-09 12:05:39
Unity中使用反射机制调用函数,供大家参考,具体内容如下
我们在进行开发时有时会碰到使用反射机制来处理事件消息,下面就是一种使用反射机制处理消息的方法
示例代码
共有两个脚本,其中一个模拟消息处理类,一个模拟使用类
using System.Reflection; using UnityEngine; using UnityEngine.UI; public class ReflectionTest : MonoBehaviour { public Button bt0; public Button bt1; public Button bt2; void Start() { bt0.onClick.AddListener(() => { Reflection("NoPara"); }); bt1.onClick.AddListener(() => { Reflection("OnePara", "你好"); }); bt2.onClick.AddListener(() => { Reflection("TwoPara", "你好", 124); }); } void Reflection(string name) { string funName = name + "Msg"; MethodInfo mi = typeof(MsgHandler).GetMethod(funName); object[] o = { }; mi.Invoke(null, o); } void Reflection(string name, string str) { string funName = name + "Msg"; MethodInfo mi = typeof(MsgHandler).GetMethod(funName); object[] o = { str }; mi.Invoke(null, o); } void Reflection(string name, string str, int n) { string funName = name + "Msg"; MethodInfo mi = typeof(MsgHandler).GetMethod(funName); object[] o = { str, n }; mi.Invoke(null, o); } }
using UnityEngine; public class MsgHandler { public static void NoParaMsg() { Debug.Log("没有参数的反射消息"); } public static void OneParaMsg(string str) { Debug.Log("一个参数的反射消息,参数是:" + str); } public static void TwoParaMsg(string str, int n) { Debug.Log("二个参数的反射消息,参数是:" + str + "和" + n); } }
使用说明及效果
将脚本挂在空物体Reflection上,然后将三个按钮挂到脚本上,运行即可。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持IT技术网。
您可能感兴趣的文章:
- c#反射机制学习和利用反射获取类型信息
相关阅读
- unity实现翻页效果
- Unity中使用反射机制调用函数
- unity实现简单的贪吃蛇游戏
- Unity PC版Log的具体位置介绍
- unity android设备上查看log输出方式
- Unity 按钮添加OnClick事件操作
- Unity中的静态批处理和动态批处理操作
- Unity 按钮事件封装操作(EventTriggerListener)
- Unity 修改FBX模型动画的操作
- Unity中EventTrigger的几种使用操作
- Unity 实现给物体动态添加事件
- Unity 如何批量修改FBX模型
- Unity 点击UI与点击屏幕冲突的解决方案
- Unity中3DText显示模糊不清的解决方案
- unity 如何判断鼠标是否在哪个UI上(两种方法)
- Unity 实现鼠标滑过UI时触发动画的操作
- unity 鼠标移入弹出UI的操作
- Unity 如何设定 Animator分割播放