0

[2]自定义Lua解析方式 - 畅知

 1 week ago
source link: https://www.cnblogs.com/TonyCode/p/18174146
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

[2]自定义Lua解析方式

在上文中我们学会学会更改加载路径,加载对应文件夹下的Lua脚本。

默认解析加载的lua脚本存在的文件位置非AB包或者Resources文件夹下往往不能随包体更新,这显然不符合热更需要。因此自定义继承

tolua中lua脚本加载解析类LuaFileUtils来重写对应的lua脚本加载方法。

public class LuaCustomLoad:LuaFileUtils { /// <summary> /// 优先从AssetBundle中加载(默认AB文件名称为lua) Resources文件夹下lua文件夹加载 /// </summary> /// <param name="fileName"></param> /// <returns></returns> public override byte[] ReadFile(string fileName) { //后缀名称检查处理 if (!fileName.EndsWith(".lua")) { fileName += ".lua"; } //二进制文件流 byte[] buffer = null; //解析路径名称 string[] tempFilePath = fileName.Split('/'); Debug.Log(tempFilePath[tempFilePath.Length - 1]); TextAsset luaText = LoadAssetBundleManager.Instance().LoadResource<TextAsset>("lua",tempFilePath[tempFilePath.Length - 1]); if (luaText != null) { buffer = luaText.bytes; } //从Resources文件夹下加载Lua脚本 if (buffer == null) { Debug.Log("从Resources资源包中加载"); string filePath = "Lua/" + fileName; //读取文件 TextAsset textAsset = Resources.Load<TextAsset>(filePath); if (textAsset != null) { buffer = textAsset.bytes; //卸载资源 Resources.UnloadAsset(textAsset); } } return buffer; } }

将lua脚本打入Resorces文件夹下(.lua文件)

img

测试:此时还未将Lua脚本打入AssetBundle包 所以从Resources文件夹下加载lua脚本。(报错是因为AssetBundle文件不存在!后期可以完善此lua文件加载脚本逻辑)

image-20240505231011403

现在我们将lua脚本打入AssetBundle中

此处踩坑:Lua脚本打入AB包失败!将lua脚本后缀添加 [.txt] ,打包之前将toLua脚本清空。

image-20240505231519714

测试使用自定义脚本要点:

在使用LuaState之前先实例化自定义的加载方法:

image-20240505235459972

这样,继承的LuaFileUtils的自定义类会调用其构造函数,将子类实例化的this赋值给instance,从而执行子类重写的ReadFile方法。

img

测试代码:

image-20240505235825015

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK