Unity中使用反射機制調(diào)用函數(shù)
更新時間:2021年03月09日 07:19:11 作者:FutureDr
這篇文章主要為大家詳細介紹了Unity中使用反射機制調(diào)用函數(shù),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
Unity中使用反射機制調(diào)用函數(shù),供大家參考,具體內(nèi)容如下
我們在進行開發(fā)時有時會碰到使用反射機制來處理事件消息,下面就是一種使用反射機制處理消息的方法
示例代碼
共有兩個腳本,其中一個模擬消息處理類,一個模擬使用類
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("一個參數(shù)的反射消息,參數(shù)是:" + str); } public static void TwoParaMsg(string str, int n) { Debug.Log("二個參數(shù)的反射消息,參數(shù)是:" + str + "和" + n); } }
使用說明及效果
將腳本掛在空物體Reflection上,然后將三個按鈕掛到腳本上,運行即可。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C#中const,readonly和static關(guān)鍵字的用法介紹
這篇文章介紹了C#中const,readonly和static關(guān)鍵字的用法,文中通過示例代碼介紹的非常詳細。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-08-08C#微信公眾平臺開發(fā)之a(chǎn)ccess_token的獲取存儲與更新
這篇文章主要介紹了C#微信公眾平臺開發(fā)之a(chǎn)ccess_token的獲取存儲與更新的相關(guān)資料,需要的朋友可以參考下2016-03-03