工作的时候,看到了主程王哥写的扩展上有一键创建lua脚本模板的扩展,在网上搜索到了相关一键创建的文章,然后自己也写了一个,具体代码如下:
using UnityEngine;
using UnityEditor;
using System.IO;
using UnityEditor.ProjectWindowCallback;
using System.Text;
using System.Text.RegularExpressions;
/// <summary>
/// Assets文件夹资源鼠标选中后右键点击的扩展
/// </summary>
public class Editor_Test1
{
/// <summary>
/// 模板路径
/// </summary>
private static string ScriptsUrl = "Assets/Scripts/LuaScipts/TestModel/ExamplePanel.lua";
/// <summary>
/// 脚本图标
/// </summary>
private static Texture2D icon = Resources.Load("luaIcon") as Texture2D;
/// <summary>
/// 创建lua脚本
/// </summary>
[MenuItem("Assets/Create/LuaScripts", false, 3)]
static void CretaeLusScripts()
{
ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance<CreateLuaScripts>(), GetSelectedPathOrFallback() + "/ExamplePanel.lua", icon, ScriptsUrl);
}
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 CreateLuaScripts: EndNameEditAction
{
public override void Action(int instanceId, string pathName, string resourceFile)
{
UnityEngine.Object o = CreateScriptAssetFromTemplate(pathName, resourceFile);
ProjectWindowUtil.ShowCreatedAsset(o);
}
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 fileNameWithoutExtension = Path.GetFileNameWithoutExtension(pathName);
text = Regex.Replace(text, "#NAME#", fileNameWithoutExtension);
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));
}
}