xlua菜鸟初学(二)

接上文对unity的设置,现在我们可以尝试制作第一个补丁
1.首先在unity制作一个简单的脚本

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;

[Hotfix ]
public class Creat_cube : MonoBehaviour {

    public GameObject cube;
    [LuaCallCSharp ]
    public void Start()
    {
        for(int i = 0; i < 5; i++)
        {
            GameObject go = Instantiate(cube, transform.position+new Vector3 (2+i*5,0,0), transform.rotation);
            print_number("66");
            print_char("aa");
        }
    }
    public void print_number(string t)
    {
        Debug.Log(t);
    }
    private void print_char(string t)
    {
        Debug.Log(t);
    }
}

在容易出问题或要修改的类中,需要添加[hotfix]。在要需要修改的方法中,如果lua调用c#方法则需要打上[LuaCallCsharp]

接下来,我们用lua对这个脚本进行修改,使生成方块的数目改变,以及输出的数目。
2.在本地中添加两个txt:
hello.lua.txt
第一个txt为修改内容

xlua.private_accessible(CS.Creat_cube)
xlua.hotfix(CS.Creat_cube,'Start',function(self)
	for i=0,2,1 do
	    local go=CS.UnityEngine.GameObject.Instantiate(self.cube, self.transform.position+CS.UnityEngine.Vector3(10 * i + 5, 0, 0), self.transform.rotation);
	    self.print_number(self,'88')
		self:print_char('bb')
	end
end)

注意,如果调用类中的静态方法时,不需要传递自身。如果调用成员的普通方法时要传递自身或者用 Self:方法名()

fish.lua.txt
第二个txt为释放lua
xlua.hotfix(CS.Creat_cube,‘Start’,nil)

3.在unity调用txt,需要再添加一个脚本

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;
using System.IO;
public class HoFixScripts : MonoBehaviour {

    private LuaEnv luaenv;
	// Use this for initialization
	void Awake () {
        luaenv = new LuaEnv();
        luaenv.AddLoader(byte_text);
        luaenv.DoString("require'hello'");
	}
	
    private byte [] byte_text(ref string filepath)
    {
        string abs = @"D:\" + filepath +".lua.txt";
    
        return System.Text.Encoding.UTF8.GetBytes(File.ReadAllText(abs));
    }
    private void OnDisable()
    {
        luaenv.DoString("require'fish'");
    }
    private void OnDestroy()
    {
        luaenv.Dispose();
    }
  
}

注意要保证此调用脚本为最先调用,保证先后顺序,防止还未被修改脚本先运行。

4.进行运行
注意每次修改c#脚本后都需要点击xlua的Generate Code 和 Hofix Inject In Editor
如果出现这个就表示成功
在这里插入图片描述
最后成果
在这里插入图片描述

发布了10 篇原创文章 · 获赞 0 · 访问量 141

猜你喜欢

转载自blog.csdn.net/qq_39121279/article/details/104246204