Unity中使用Xlua调用lua相关

cs 复制代码
//引用命名空间
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包中读取,所以需要自定义加载路径

cs 复制代码
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')");
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="filePath">Lua脚本文件名</param>
    /// <returns></returns>
    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下查找

相关推荐
WarrenMondeville14 分钟前
4.Unity面向对象-接口隔离原则
java·unity·接口隔离原则
WarrenMondeville2 小时前
3.Unity面向对象-里氏替换原则
unity·游戏引擎·里氏替换原则
WarrenMondeville3 小时前
5.Unity面向对象-依赖倒置原则
unity·设计模式·依赖倒置原则
万兴丶4 小时前
Unity 用AI自动开发游戏近一年----最新Cursor使用心得
人工智能·游戏·unity·cursor
张老师带你学16 小时前
UnityVR弯曲UI
科技·游戏·unity·游戏引擎·模型
张老师带你学17 小时前
unity作业,街角小场景
科技·游戏·unity·游戏引擎·模型
mxwin20 小时前
Unity Shader LOD:动态 Shader 等级切换技术详解
unity·游戏引擎·shader
ALex_zry20 小时前
C++高性能日志与监控系统设计
c++·unity·wpf
魔士于安1 天前
Unity太空战舰完整工程,包含战损,实时战损
游戏·unity·游戏引擎·贴图·模型
Nuopiane1 天前
MyPal3(10)视锥体剔除
unity