含参函数调用
回到HotFix工程,添加一个含参的静态函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| using UnityEngine;
namespace HotFix { public class TestClass { public static void StaticFuncTest() { Debug.Log("Test"); } public static void StaticFuncTest2(int a) { Debug.Log("Test param a = " + a); } } }
|
在之前,我们使用了方法名直接调用了热更代码
1
| m_AppDomain.Invoke("HotFix.TestClass", "StaticFuncTest", null, null);
|
第一个参数传入程序集和类名,第二个参数传入方法名,第三个参数是类的实例,如果是null表示调用的是静态方法,不需要实例。第四个参数表示传入的方法参数,它是一个参数数组。
我们接下来使用另一种方式来调用热更代码,修改ILRuntimeManager
的OnHotFixLoaded
方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| using ILRuntime.CLR.TypeSystem; using ILRuntime.CLR.Method;
void OnHotFixLoaded() {
IType type = m_AppDomain.LoadedTypes["HotFix.TestClass"];
IMethod method = type.GetMethod("StaticFuncTest", 0); m_AppDomain.Invoke(method,null,null); }
|
第一种方法
我们使用上面的方式来调用含参函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| void OnHotFixLoaded() {
IType type = m_AppDomain.LoadedTypes["HotFix.TestClass"];
IMethod method2 = type.GetMethod("StaticFuncTest2",1); m_AppDomain.Invoke(method2, null, 1); }
|
此时运行Unity,可以看到参数已经传入到了函数里面。
第二种方法
其实IType.GetMethod
还有一个重载,在实际使用的过程中,更推荐使用这个重载
1
| IMethod GetMethod(string name, List<IType> param, IType[] genericArguments, IType returnType = null, bool declaredOnly = false);
|
我们修改一下代码,看一下这个重载是如何使用的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| void OnHotFixLoaded() {
IType type = m_AppDomain.LoadedTypes["HotFix.TestClass"];
IType intType = m_AppDomain.GetType(typeof(int)); List<IType> paraListTypes = new List<IType>(); paraListTypes.Add(intType); IMethod method2 = type.GetMethod("StaticFuncTest2",paraListTypes,null); m_AppDomain.Invoke(method2, null, 1); }
|
此时运行Unity,可以看到参数已经传入到了函数里面。