实例化热更里的类
实例化热更里的类
Debug.Log("实例化热更里的类");
object obj = appdomain.Instantiate("HotFix_Project.InstanceClass", new object[] { 233 });
//第二种方式
IType type = appdomain.LoadedTypes["HotFix_Project.InstanceClass"];
object obj2 = ((ILType)type).Instantiate();
调用成员方法
Debug.Log("调用成员方法");
method = type.GetMethod("get_ID", 0);
using (var ctx = appdomain.BeginInvoke(method))
{
ctx.PushObject(obj);
ctx.Invoke();
int id = ctx.ReadInteger();
Debug.Log("!! HotFix_Project.InstanceClass.ID = " + id);
}
using (var ctx = appdomain.BeginInvoke(method))
{
ctx.PushObject(obj2);
ctx.Invoke();
int id = ctx.ReadInteger();
Debug.Log("!! HotFix_Project.InstanceClass.ID = " + id);
}
Debug.Log("调用泛型方法");
IType stringType = appdomain.GetType(typeof(string));
IType[] genericArguments = new IType[] { stringType };
appdomain.InvokeGenericMethod("HotFix_Project.InstanceClass", "GenericMethod", genericArguments, null, "TestString");
Debug.Log("获取泛型方法的IMethod");
paramList.Clear();
paramList.Add(intType);
genericArguments = new IType[] { intType };
method = type.GetMethod("GenericMethod", paramList, genericArguments);
appdomain.Invoke(method, null, 33333);
Debug.Log("调用带Ref/Out参数的方法");
method = type.GetMethod("RefOutMethod", 3);
int initialVal = 500;
using(var ctx = appdomain.BeginInvoke(method))
{
//第一个ref/out参数初始值
ctx.PushObject(null);
//第二个ref/out参数初始值
ctx.PushInteger(initialVal);
//压入this
ctx.PushObject(obj);
//压入参数1:addition
ctx.PushInteger(100);
//压入参数2: lst,由于是ref/out,需要压引用,这里是引用0号位,也就是第一个PushObject的位置
ctx.PushReference(0);
//压入参数3,val,同ref/out
ctx.PushReference(1);
ctx.Invoke();
//读取0号位的值
List<int> lst = ctx.ReadObject<List<int>>(0);
initialVal = ctx.ReadInteger(1);
Debug.Log(string.Format("lst[0]={0}, initialVal={1}", lst[0], initialVal));
}
HotFix_Project
项目的 InstanceClass.cs
文件
using System;
using System.Collections.Generic;
namespace HotFix_Project
{
public class InstanceClass
{
private int id;
public InstanceClass()
{
UnityEngine.Debug.Log("!!! InstanceClass::InstanceClass()");
this.id = 0;
}
public InstanceClass(int id)
{
UnityEngine.Debug.Log("!!! InstanceClass::InstanceClass() id = " + id);
this.id = id;
}
public int ID
{
get { return id; }
}
// static method
public static void StaticFunTest()
{
UnityEngine.Debug.Log("!!! InstanceClass.StaticFunTest()");
}
public static void StaticFunTest2(int a)
{
UnityEngine.Debug.Log("!!! InstanceClass.StaticFunTest2(), a=" + a);
}
public static void GenericMethod<T>(T a)
{
UnityEngine.Debug.Log("!!! InstanceClass.GenericMethod(), a=" + a);
}
public void RefOutMethod(int addition, out List<int> lst, ref int val)
{
val = val + addition + id;
lst = new List<int>();
lst.Add(id);
}
}
}