xLua learning summary (5) --- hot update

It is the most important function of xLua to use xLua to hot update the logic functions completed in C# in unity.

Preparation:

1. Add HOTFIX_ENABLE path File-BuildSettings-PlayerSettings-OtherSettings to ScriptingDefineSymbols

2. Put the label [Hotfix] on the class that may need hot update

3. Put the label [LuaCallCSharp] on the method that may need hot update

4. GenerateCode HotFix Inject In Editor is required after each modification of a class that needs to be hot-updated (during the development process, it is not required after packaging)

Example: modifying the display of text in a UI panel

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";       
    }
}

Originally displayed as follows

After the game is packaged, the display content needs to be hot-updated, that is, the ShowText method in the UIPanel class is hot-updated. The corresponding lua code is as follows

xlua.hotfix(CS.UIPanel,"ShowText",function(self)
  self.text1.text="更新後"
  self.text2.text="更新後1"
  self.num=2; 
end
)

Effect after hot update:

(Note that calling the hot update code of lua needs to be earlier than the original call of the method ShowText in the class UIPanel in C#, that is, the hot update needs to be completed before the method is called!!!)

Note that after closing the game, the following error will be reported

Need to release the corresponding hot update reference before closing the game, you can execute DisposeHotFix in OnDestroy

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));
    }
}

The DisposeHotFix file is as follows

xlua.hotfix(CS.UIPanel,"ShowText",nil)

 

Guess you like

Origin blog.csdn.net/l17768346260/article/details/103669563