Unity中使用反射機(jī)制調(diào)用函數(shù)
Unity中使用反射機(jī)制調(diào)用函數(shù),供大家參考,具體內(nèi)容如下
我們在進(jìn)行開發(fā)時(shí)有時(shí)會(huì)碰到使用反射機(jī)制來處理事件消息,下面就是一種使用反射機(jī)制處理消息的方法
示例代碼
共有兩個(gè)腳本,其中一個(gè)模擬消息處理類,一個(gè)模擬使用類
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("沒有參數(shù)的反射消息");
}
public static void OneParaMsg(string str)
{
Debug.Log("一個(gè)參數(shù)的反射消息,參數(shù)是:" + str);
}
public static void TwoParaMsg(string str, int n)
{
Debug.Log("二個(gè)參數(shù)的反射消息,參數(shù)是:" + str + "和" + n);
}
}
使用說明及效果
將腳本掛在空物體Reflection上,然后將三個(gè)按鈕掛到腳本上,運(yùn)行即可。


以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C#的鋸齒數(shù)組以及C++實(shí)現(xiàn)代碼
鋸齒數(shù)組首先是二維數(shù)組,第一維的維數(shù)是確定的。之所以在C#中能夠出現(xiàn)靈活的鋸齒數(shù)組,是因?yàn)?,C#的數(shù)組是引用類型(本質(zhì)上存放的是指針)。根據(jù)這個(gè)引用類型(指針)的概念,C++中用指針數(shù)組同樣可以實(shí)現(xiàn)2013-09-09
C#中const,readonly和static關(guān)鍵字的用法介紹
這篇文章介紹了C#中const,readonly和static關(guān)鍵字的用法,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-08-08
C#微信公眾平臺(tái)開發(fā)之a(chǎn)ccess_token的獲取存儲(chǔ)與更新
這篇文章主要介紹了C#微信公眾平臺(tái)開發(fā)之a(chǎn)ccess_token的獲取存儲(chǔ)與更新的相關(guān)資料,需要的朋友可以參考下2016-03-03
C# SDK實(shí)現(xiàn)百度云OCR的文字識(shí)別功能
這篇文章主要為大家詳細(xì)介紹了C# SDK實(shí)現(xiàn)百度云OCR的文字識(shí)別功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-11-11
C#托管堆對(duì)象實(shí)例包含內(nèi)容分析
這篇文章主要介紹了C#托管堆對(duì)象實(shí)例包含內(nèi)容,實(shí)例展示了托管對(duì)象的結(jié)構(gòu)及運(yùn)行原理,需要的朋友可以參考下2014-09-09

