Unity Xlua之Hotfix热补丁 (一)
一.第一个热补丁
- 想要打热补丁的类前需要加上[Hotfix]特性
- 第一次打热补丁需要加上宏HOTFIX_ENABLE
- 点击生成代码
- 点击注入热补丁
例如我想修改如下代码中的两个方法,无论是公有方法还是私有方法都可以修改
[Hotfix]
public class HotfixMain : MonoBehaviour
{
private void Start()
{
LuaMgr.GetInstance().Init();
LuaMgr.GetInstance().LoadFile("Main");
print(Add(10, 20));
Speak("zzs");
}
public int Add(int a,int b){
return 0;
}
public static void Speak(string str){
Debug.Log("123");
}
}
print("Hotfix01 开始执行!")
xlua.hotfix(CS.HotfixMain,"Add",function (self,a,b)
return a + b
end)
xlua.hotfix(CS.HotfixMain,"Speak",function (str)
CS.UnityEngine.Debug.Log(str)
end)
二.多函数替换,构造析构替换
- 替换构造函数和析构函数与其它的函数不同,这两种构造函数是先执行C#中的构造和析构再执行Lua中的构造和析构
[Hotfix]
public class TestHotfix
{
public TestHotfix()
{
Debug.Log("C#构造函数执行");
}
public void Speak(string str)
{
Debug.Log("123");
}
~TestHotfix(){
Debug.Log("C#析构函数调用");
}
}
print("Hotfix02 开始执行!")
xlua.hotfix(CS.TestHotfix,
{
[".ctor"] = function()
print("Lua构造函数")
end,
Speak = function(self,str)
print(str)
end,
Finalize = function()
print("Lua析构函数调用")
end
})
三.协程替换
- 如果修改原来函数的内容不需要重新生成代码,只有添加了函数需要重新生成代码
private IEnumerator TestEnumerator(){
while (true)
{
yield return new WaitForSeconds(1f);
Debug.Log("C#执行");
}
}
print("Hotfix03 开始执行!")
util = require("xlua.util")
xlua.hotfix(CS.HotfixMain,{
TestEnumerator = function()
return util.cs_generator(function()
while true do
coroutine.yield(CS.UnityEngine.WaitForSeconds(0.1))
print("Lua执行")
end
end)
end
})