Unity 3D - 编辑器扩展之创建lua文件模版 :
创建方法 :
作用 :
- 利用正则自动生成文件路径 , 类名 等文件信息 .
- 在模版上加一些创建提示 , 方便后面开发 .
自动生成结果 :
C# 文件内容 :
using UnityEngine;
using UnityEditor;
using System;
using System.IO;
using System.Text;
using UnityEditor.ProjectWindowCallback;
using System.Text.RegularExpressions;
public class AutoLuaCreator
{
[MenuItem("Assets/Create/Lua Script", false, 80)]
public static void CreatController()
{
ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0,
ScriptableObject.CreateInstance<MyDoCreateScriptAsset>(),
GetSelectedPathOrFallback() + "/New lua.lua", //创建文件初始名
null,
"Assets/Editor/template/Newlua.lua"); //模版路径
}
public static string GetSelectedPathOrFallback()
{
string path = "Assets";
foreach (UnityEngine.Object obj in Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.Assets))
{
path = AssetDatabase.GetAssetPath(obj);
if (!string.IsNullOrEmpty(path) && File.Exists(path))
{
path = Path.GetDirectoryName(path);
break;
}
}
return path;
}
}
class MyDoCreateScriptAsset : EndNameEditAction
{
public override void Action(int instanceId, string pathName, string resourceFile)
{
UnityEngine.Object o = CreateScriptAssetFromTemplate(pathName, resourceFile);
ProjectWindowUtil.ShowCreatedAsset(o);
}
//获取MainGame文件夹下的路径名
public static string getLuaPath(string fullPath)
{
string luaPath = "";
string[] pathArr = fullPath.Split(new string[] { "\\" }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < pathArr.Length; i++)
{
if (pathArr[i] == "MainGame")
{
//处理创建文件路径
for (int j = i; j < pathArr.Length - 1; j++)
{
luaPath += pathArr[j] + ".";
}
break;
}
}
return luaPath;
}
internal static UnityEngine.Object CreateScriptAssetFromTemplate(string pathName, string resourceFile)
{
string fullPath = Path.GetFullPath(pathName); //完整路径
StreamReader streamReader = new StreamReader(resourceFile);
string text = streamReader.ReadToEnd();
streamReader.Close();
string fileName = Path.GetFileNameWithoutExtension(pathName); //文件名
string luaPath = getLuaPath(fullPath); //lua路径
//正则替换
text = Regex.Replace(text, "#NAME#", fileName);
text = Regex.Replace(text, "#PATH#", luaPath);
bool encoderShouldEmitUTF8Identifier = true;
bool throwOnInvalidBytes = false;
UTF8Encoding encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier, throwOnInvalidBytes);
bool append = false;
StreamWriter streamWriter = new StreamWriter(fullPath, append, encoding);
streamWriter.Write(text);
streamWriter.Close();
AssetDatabase.ImportAsset(pathName);
return AssetDatabase.LoadAssetAtPath(pathName, typeof(UnityEngine.Object));
}
}