123456881 发表于 2021-3-12 07:06

MacOS下InjectFix 热更Unity C#代码

InjectFix是腾讯开源的一个用于热修复unity c#代码的工具,本文演示一下在macOS下的使用方法。
clone项目代码
2. 修改Source/VSProj/build_for_unity.sh文件内容,此处需要注意的是从mono 2.11开始,引入了mcs来替换 gmcs、smcs、dmcs。
UNITY_HOME="/Applications/Unity/Unity.app"
GMCS="$UNITY_HOME/Contents/MonoBleedingEdge/bin/mcs"
MONO="$UNITY_HOME/Contents/MonoBleedingEdge/bin/mono"3. 编译项目
./build_for_unity.sh4. 新建测试项目,并且将Source/UnityProj/IFixToolKit拷贝到测试项目下,和Assets同路径。
http://pic2.zhimg.com/v2-d48ca85b175b0a29aa16d346f3a44c5_b.jpg5. 拷贝Source/UnityProj/Assets/IFix到测试项目的Assets下面,拷贝Source/UnityProj/Assets/Plugins/IFix.Core.dll 拷贝到测试项目的Assets/Plugins下面。
6. 在IFix/Editor目录下创建配置文件HotFixCfg.cs
using System.Collections.Generic;
using IFix;
using System;
using System.Reflection;

//1、配置类必须打标签
//2、必须放Editor目录


public class HotFixCfg
{
   
    static IEnumerable<Type> hotfix
    {
      get
      {
            return Assembly.Load("Assembly-CSharp").GetTypes();
      }
    }
}
7. 新建Test.cs脚本,并且挂到一个GameObject上。InjectFix热更需要Inject来做一些预处理,然后再Fix来创建补丁。所以在修改代码之后不能inject,否则会认为这是一个线上版本,拒绝创建补丁。为了测试方便,我们先创建一个补丁版本,然后在修改为基版本来inject模拟有问题的版本。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using IFix.Core;
using IFix;


public class Test : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
      string PatchFile = "Assets/IFix/Resources/Assembly-CSharp.patch.bytes";
      if (File.Exists(PatchFile))
      {
            PatchManager.Load(PatchFile);
      }
      HelloWorld();
    }

    // Update is called once per frame
    void Update()
    {
      
    }

   
    void HelloWorld()
    {
      Debug.Log("hello world");
    }
}
8. 执行InjectFix/Fix,可以看到Console打印成功的信息,并且在项目根目录下生成了补丁文件Assembly-CSharp.patch.bytes。
9. 将代码修改为错误版本,然后Inject。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using IFix.Core;


public class Test : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
      string PatchFile = "Assets/IFix/Resources/Assembly-CSharp.patch.bytes";
      if (File.Exists(PatchFile))
      {
            PatchManager.Load(PatchFile);
      }
      HelloWorld();
    }

    // Update is called once per frame
    void Update()
    {
      
    }

    void HelloWorld()
    {
      Debug.Log("hell world");
    }
}
10. 将之前生成的补丁文件,放到Assets/IFix/Resources下面,运行项目,可以看到输出为正确结果。
页: [1]
查看完整版本: MacOS下InjectFix 热更Unity C#代码