unity 热重载方式加载 dll

1.代码示例

    void LoadDll() {
        //Unity版本对于Load Dll的影响
        //2019 就算在运行时修改了dll,也是无效的,拿的还是上一次的dll
        //2020 unity认为相同路径为上一次的dll
        //2021 没问题
        
        //读取相对路径文件夹下的某种名称的 dll
        string BuildOutputDir = "./Temp/Bin/Debug";
        string[] logicFiles = Directory.GetFiles(BuildOutputDir, "My*.dll");

        if (logicFiles.Length != 1)
        {
            throw new Exception("Logic dll count != 1");
        }

        string logicName = Path.GetFileNameWithoutExtension(logicFiles[0]);
        byte[] assBytes = File.ReadAllBytes(Path.Combine(BuildOutputDir, $"{logicName}.dll"));
        byte[] pdbBytes = File.ReadAllBytes(Path.Combine(BuildOutputDir, $"{logicName}.pdb"));
        //通过 dll 和 pdb 加载程序集
        Assembly hotfixAssembly = Assembly.Load(assBytes, pdbBytes);

        //实例化调用 dll 方法,也可以用静态的
        Type type = hotfixAssembly.GetType("TestCode.Class1");
        object obj = Activator.CreateInstance(type);
        MethodInfo methodInfo = type.GetMethod("Test");
        methodInfo.Invoke(obj, null);
    }

 

2.添加独立工程

在用代码编辑器打开的工程里面,添加一个类库工程,类库工程负责生成 dll ,主工程去读取这个dll文件

 

posted @ 2023-01-04 13:58  三页菌  阅读(496)  评论(0编辑  收藏  举报