开发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);
}
}
}