- //引用命名空间
- using XLua;
- public class L1 : MonoBehaviour
- {
- // Start is called before the first frame update
- void Start()
- {
- //Lua解析器 让我们在Unity中使用lua
- LuaEnv env = new LuaEnv();
-
- //执行
- env.DoString("print('OK')");
- //执行一个Lua脚本 在resource文件夹下
- env.DoString("require('Main')");
- //垃圾回收
- env.Tick();
-
- //销毁Lua解析器
- env.Dispose();
-
-
- }
- }
这样只能读取Resources文件夹下的脚本,但是我们做热更新需要从AB包中读取,所以需要自定义加载路径
- public class L2 : MonoBehaviour
- {
- // Start is called before the first frame update
- void Start()
- {
- LuaEnv env = new LuaEnv();
- //XLua提供的路径重定向方法
- //自定义加载Lua文件的规则
- env.AddLoader(MyLoader);
-
- env.DoString("require('Main')");
- }
- ///
- ///
- ///
- /// Lua脚本文件名
- ///
- private byte[] MyLoader(ref string filePath)
- {
- //在这里自定义加载逻辑
- string path = Application.dataPath + "/Lua/" + filePath + ".lua";
- //得到路径后加载文件
- //引用命名空间
- if (File.Exists(path))
- {
- return File.ReadAllBytes(path);
- }
- else
- {
- print("MyLoader加载失败,文件名为"+path);
- return null;
- }
- }
- }
require寻找文件的逻辑是,先找AddLoader中自定义的路径(可以有多个路径)中有没有相应文件,再去Resources下查找