在Unity中使用Lua脚本模板创建新的Lua文件
使用情景
在开发中我们经常会创建适合自己使用的一些基类或者文件模版,在使用的时候就需要经常去复制文件,这个时候我们可以创建一个文件模板,然后在unity的Project窗口中直接右键创建脚本模板。
1.使用效果
2.创建的文件
3.文件内容
工具制作方法
1.在Assets下创建一个Editor文件夹,已经存在Editor文件夹的略过此步骤
2.在文件夹下创建自己的工具文件夹,名字按照自己的习惯命名,或根据项目规则统一命名
3.在上面的文件夹下用c#创建一个工具类
代码如下,可以根据自己的需求修改:
using UnityEngine;
using UnityEditor;
using System;
using System.IO;
using System.Text;
using UnityEditor.ProjectWindowCallback;
using System.Text.RegularExpressions;
public class CreateMyLua
{
[MenuItem("Assets/Create/Lua Script", false, 80)]
public static void CreatLuaFile()
{
ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0,
ScriptableObject.CreateInstance<MyDoCreateScriptAsset>(),
GetSelectedPathOrFallback() + "/New Lua.lua",
null,
"Assets/Editor/LuaCreateTool/lua.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);
}
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));
}
}
4.在文件夹下创建一个Lua脚本模板,命名随意,但是要和上面C#脚本中的”Assets/Editor/LuaCreateTool/lua.lua”保持一致,Lua脚本的内容按照自己的模板填写即可。
local class = require('middleclass')
local NewClass = class("NewClass")
function NewClass:initialize()
end
return NewClass;