使用xLua对unity中用C#完成的逻辑功能进行热更新,是xLua最重要的功能。
准备工作:
1.ScriptingDefineSymbols中加入HOTFIX_ENABLE 路径File-BuildSettings-PlayerSettings-OtherSettings
2.在有可能需要热更新的类上打上[Hotfix]标签
3.在有可能需要热更新的方法上打上[LuaCallCSharp]标签
4.每次修改完需要热更新的类后,都要GenerateCode HotFix Inject In Editor(开发过程中,打包后是不需要的)
例子:修改一个UI面板中文字的显示
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;
using UnityEngine.UI;
[Hotfix]
public class UIPanel : MonoBehaviour {
public Text text1;
private Text text2;
private int num = 1;
// Use this for initialization
void Start () {
text2 = transform.Find("Text2").GetComponent<Text>();
ShowText();
Debug.Log("num:"+num);
}
[LuaCallCSharp]
public void ShowText()
{
text1.text = "更新前1";
text2.text = "更新前2";
}
}
原本显示如下
游戏打包后,需要热更新显示内容,即热更新UIPanel类中的ShowText方法,相应的lua代码如下
xlua.hotfix(CS.UIPanel,"ShowText",function(self)
self.text1.text="更新後"
self.text2.text="更新後1"
self.num=2;
end
)
热更新后效果:
(注意调用lua的热更新代码,需要早于C#中类UIPanel原本对于方法ShowText的调用,即在方法调用前需要完成热更新!!!)
注意在关闭游戏后,会有如下报错
需要在关闭游戏前释放掉相应的热更新引用,可以OnDestroy中执行DisposeHotFix
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using XLua;
public class EntryLua : MonoBehaviour {
LuaEnv env;
// Use this for initialization
void Awake () {
env = new LuaEnv();
env.AddLoader(customerLoader);
env.DoString("require 'HotFix'");
}
private void OnDestroy()
{
env.DoString("require 'DisposeHotFix'");//結束後反註冊
env.Dispose();
}
private byte[] customerLoader(ref string path)
{
string filePath = Application.streamingAssetsPath + "/"+path + ".lua.txt";
return System.Text.Encoding.UTF8.GetBytes(File.ReadAllText(filePath));
}
}
DisposeHotFix文件如下
xlua.hotfix(CS.UIPanel,"ShowText",nil)