Unity反射机制调用函数 Unity中使用反射机制调用函数

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Unity反射机制调用函数 Unity中使用反射机制调用函数

FutureDr   2021-03-15 我要评论
想了解Unity中使用反射机制调用函数的相关内容吗,FutureDr在本文为您仔细讲解Unity反射机制调用函数的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Unity,反射机制,函数,下面大家一起来学习吧。

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上,然后将三个按钮挂到脚本上,运行即可。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们