保留.lua后缀名,将lua文件打包成assetbundle

开发ulua的同志们一定遇见过一个很大的坑,就是将lua文件打包成assetbundle的时候,unity引擎不识别lua文件,最后只好绕弯路把lua文件改成txt文件,然后才能打包。最后开发的时候,直接就用txt进行开发。这样子网上那么多lua的编辑器基本上都用不了,代码提示,跟代码查错都将给一些人很大的困扰,对于刚刚学习lua的人来说简直就是一种非常大的打击,从而使开发的门槛变高,对于整个项目来说是不利的。


对此我选择了一种曲线救国的方式,思想是打包assetbundle的时候,将.lua文件拷贝一份,在同一路径下存成.txt文件。然后调用打包assetbundle的指令,进行打包,打包完成后删除txt文件,从而让使用者只管在.lua文件里面开发就行。


直接上UnityEditor的代码。(不是很优雅,但是估计也勉强看得懂)

using UnityEngine;
using UnityEditor;
using System.IO;

public class ExportAssetBundles {

    //在Unity编辑器中添加菜单  
    [MenuItem("Assets/Build AssetBundle From Selection")]
    static void ExportResourceRGB2() {

        // 打开保存面板,获得用户选择的路径  
        string path = EditorUtility.SaveFolderPanel("Select Lua Script Folder", "", "");
        DirectoryInfo TheFolder = new DirectoryInfo(path);
        string bundlePath = path + "/" + TheFolder.Name + ".assetbundle";
        ChangeLua2Txt(TheFolder, path);

        bundlePath = EditorUtility.SaveFilePanel("Save Resource", "", TheFolder.Name, "assetbundle");
        AssetDatabase.Refresh();
        if (path.Length != 0) {
            // 选择的要保存的对象
            Object[] selection = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);
            //打包
            BuildPipeline.BuildAssetBundle(Selection.activeObject, selection, bundlePath, BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets, BuildTarget.StandaloneWindows);
            DeleteTxt(TheFolder);
            AssetDatabase.Refresh();
        }
    }
    static private void ChangeLua2Txt(DirectoryInfo TheFolder, string path) {
        foreach (var NextFile in TheFolder.GetFiles("*.lua")) {
            var utf8WithoutBom = new System.Text.UTF8Encoding(false);
            StreamReader sr = new StreamReader(NextFile.FullName, utf8WithoutBom);
            string text = sr.ReadToEnd();
            FileStream fs = new FileStream(path + "/" + Path.ChangeExtension(NextFile.Name, "txt"), FileMode.Create);
            StreamWriter sw = new StreamWriter(fs, utf8WithoutBom);
            sw.Write(text);

            sr.Close();

            sw.Flush();
            sw.Close();
            fs.Close();
        }
        foreach (DirectoryInfo NextFolder in TheFolder.GetDirectories()) {
            ChangeLua2Txt(NextFolder, path);
        }
    }
    static private void DeleteTxt(DirectoryInfo TheFolder) {
        foreach (var NextFile in TheFolder.GetFiles("*.txt")) {
            NextFile.Delete();
        }
        foreach (DirectoryInfo NextFolder in TheFolder.GetDirectories()) {
            DeleteTxt(NextFolder);
        }
    }
}




  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值