第一种方式:通过默认加载器加载XLua文件
1. 在Asset/Resources下建立A.lua.txt文件:
我在此输入了以下内容,方便观察效果:
2. 编写cs脚本:
using UnityEngine; using XLua; public class XLua_Mono_ByResources : MonoBehaviour { // Start is called before the first frame update void Start() { LuaEnv env = new LuaEnv(); env.DoString("require 'A'"); } }
3. 挂载至场景内的某个物体,先后点击菜单栏的Clear Generate Code和Generate Code:
4. 运行游戏后将在Console下看到:
第二种方式:通过自定义加载器加载Lua文件
1. 假设在Assets/_Scripts/XLua/_LuaScript文件夹下创建文件B.lua:
2. 编写脚本:
using System; using System.IO; using UnityEngine; using XLua; public class XLua_Mono : MonoBehaviour { private LuaEnv env = null;// Xlua解释器 // Start is called before the first frame update void Start() { env = new LuaEnv(); env.AddLoader(MyLoader); env.DoString("require 'B'"); } private void OnDisable() { try { if (env != null) { // 进行一次强制的垃圾回收 env.Tick(); // 确保在销毁时释放Lua环境 env.Dispose(); // 防止再次被引用 env = null; } Debug.Log("成功释放解释器资源"); } catch(Exception ex) { Debug .LogError("释放解释器资源时发生错误: " + ex.Message); } } private byte[] MyLoader(ref string fileName) { string filePath = Application.dataPath + "/_Scripts/_XLua/_LuaScript/" + fileName + ".lua"; if (File.Exists(filePath)) { return File.ReadAllBytes(filePath); } else { Debug.LogError("Lua file not found: " + filePath); } return null; } }
3. 挂载至场景内的某个物体,先后点击菜单栏的Clear Generate Code和Generate Code:
4. 运行游戏将看到: