Mecanim 发表于 2023-4-10 10:36

Xlua的使用

xlua下载地址: https://github.com/Tencent/xLua
下载后将Xlua文件夹复制到Assets下。
一、 调用C#方法。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;

public class HelloWord : MonoBehaviour
{
    private LuaEnv luaenv;//创建虚拟机
    // Start is called before the first frame update
    void Start()
    {
      luaenv = new LuaEnv();

      luaenv.DoString("print('Hello Xlua')");//使用lua进行编译

      //luaenv.DoString("CS.UnityEngine.Debug.Log('Xlua')");//使用unity中的debug。

      

    }
    private void OnDestroy()
    {
      luaenv.Dispose();//释放内存
    }
}二、加载lua源文件。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;
using System.IO;

public class mybyfile : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
       // TextAsset taxt = Resources.Load<TextAsset>("helloworld");

      LuaEnv luaenv = new LuaEnv();
      //luaenv.DoString(taxt.text);
      //uaenv.DoString("require'helloworld'"); //文件名必须要使用.lua为后缀名,文件要在Resources文件夹下。

      luaenv.AddLoader(MyLoader);

      luaenv.DoString("require'textlua'");
      luaenv.Dispose();
    }

    //自定义loader
    private byte[] MyLoader(ref string filePath)
    {
      print(Application.streamingAssetsPath);

      string path = Application.streamingAssetsPath + "/" + filePath + ".lua.txt";
      
      return System.Text.Encoding.UTF8.GetBytes(File.ReadAllText(path));
    }
} 三、访问lua文件中的全局变量
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;

public class CSharpLua : MonoBehaviour
{
    void Start()
    {
      LuaEnv env = new LuaEnv();
      env.DoString("require 'Csharplua'");
      var a = env.Global.Get<int>("a");//获取lua里边的全局变量
      var b = env.Global.Get<string>("str");//获取lua里边的全局变量
      var c = env.Global.Get<bool>("mybool");//获取lua里边的全局变量
      print(a);
      print(b);
      print(c);

      //访问lua中的table,映射到class中
      Per p = env.Global.Get<Per>("person");
      print(p.name + " " + p.age);
      env.Dispose();
      
    }

   class Per
    {
      public string name;
      public int age;
    }


}四、lua脚本修改C#中的方法
    //重新定义c#方法中的内容
    local engine=CS.UnityEngine

        xlua.hotfix(CS.Treasour,'CreatePrize',function(self)
                print("1111")
    end)//{0}要修改的函数所在类名,{1}要修改的方法名,{2}修改后的方法
      //修改的脚本中需要添加标签,要修改的方法添加标签。

    //基于原方法新增内容
    local util= require 'util'
        xlua.private_accessible(CS.Boss)//使用类中的私有成员变量
        util.hotfix_ex(CS.Boss,'Start',function(self)
                self.Start(self)//执行一次原方法中的内容
      print(self.name)//新增内容
        end)//注意需要将util.lua文件提前导入工程。
页: [1]
查看完整版本: Xlua的使用