热更新工具--lua文件迁移脚本学习笔记

2021/4/9 18:55:53

本文主要是介绍热更新工具--lua文件迁移脚本学习笔记,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

一.简介

  在Unity中,使用AssetBundle Browser打包时,这个工具无法识别.lua后缀的文件,lua代码无法直接打包。我们可以为lua文件添加上后缀.txt以修改lua文件格式的方式解决这个问题,文件内容不会修改。但是对于一个项目,lua文件非常多,这时显然一个一个修改太过于麻烦,因此这个脚本让我们可以在Unity中一键复制所有的lua文件到一个新文件夹中,并将这些lua文件添加到名称为lua的AB包中,迁移后直接使用AssetBundle Browser打包即可。

二.代码:

public class LuaCopyEditor : Editor
{
    [MenuItem("XLua//Copy lua to txt file")]
    public static void CopyLuaToTxtFile(){
        //找到lua文件路径
        string path = Application.dataPath + "/Lua/";
        //校验路径是否存在
        if(!Directory.Exists(path))
            return;
        //得到每个lua文件路径
        string[] luaFiles = Directory.GetFiles(path,"*.lua");

        //确定一个新路径
        string txtPath = Application.dataPath + "/LuaTxt/";
        //校验新路径文件是否存在
        if(!Directory.Exists(txtPath))
            //不存在创建
            Directory.CreateDirectory(txtPath);
        else{
            //存在清空文件夹
            string[] oldFiles = Directory.GetFiles(txtPath);
            foreach(string tempOldPath in oldFiles){
                File.Delete(tempOldPath);
            }
        }
        //遍历拷贝
        string tempPath = "";
        List<string> txtFilePaths = new List<string>();
        foreach (string str in luaFiles)
        {
            //得到新路径
            tempPath = txtPath + str.Substring(str.LastIndexOf("/")+1) + ".txt";
            txtFilePaths.Add(tempPath);
            File.Copy(str,tempPath);
        }

        //刷新Unity
        AssetDatabase.Refresh();

        //修改AB包打包
        foreach(string str in txtFilePaths){
            AssetImporter importer = AssetImporter.GetAtPath(str.Substring(str.IndexOf("Assets")));
            if(importer != null)
                importer.assetBundleName = "lua";
        }
    }
}

三.注意事项

  这个脚本在运行时如果xlua生成的代码没有清空会报错,记得清除所有xlua生成的脚本,在迁移完成后重新生成代码。



这篇关于热更新工具--lua文件迁移脚本学习笔记的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程