【Unity编辑器扩展实践】、基于模板创建Lua脚本

当前项目使用C#开发版本,IOS使用Xlua热更代码。每次创建Xlua文件的时候,都是复制之前的Lua文件修改文件名、类名,模板内容基本一致,觉得有一点麻烦。

以前写过一篇文章:修改Unity、VS2015创建C#脚本时使用的模板,就想仿照着Unity创建C#脚本时的方法写一个创建Lua脚本的编辑器扩展。

首先根据需求,创建一个Txt模板:100-Lua Script-NewLua.lua.txt

local #SCRIPTNAME#Class = DeclareClass("#SCRIPTNAME#Class")

function #SCRIPTNAME#Class:HotFix()
    xlua.private_accessible(CS.#SCRIPTNAME#)
    xluaUtil.hotfix_ex(CS.#SCRIPTNAME#, "XXXXX", self.XXXXX)
    LogE("hotfix #SCRIPTNAME#Class")
end

function #SCRIPTNAME#Class.XXXXX(this, args)
	this:XXXXX(args)
end

function #SCRIPTNAME#Class:Destory()
    xlua.hotfix(CS.#SCRIPTNAME#, "XXXXX", nil)
end

添加编辑器代码,调用ProjectWindowUtil.StartNameEditingIfProjectWindowExists函数创建文件时编辑文件名称。

 [MenuItem("Assets/Create/Xlua Script",false,101)]
    static void CreateXluaHotfixField()
    {
        string _path = "Assets/XLua/Editor/100-Lua Script-NewLua.lua.txt";//模板路径
        ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0,
             ScriptableObject.CreateInstance<CreateLuaScriptAsset>(),
             GetSelectedPath(),
             null,
             _path
             );
        AssetDatabase.Refresh();
    }

    private static string GetSelectedPath()
    {
        UnityEngine.Object[] obj = Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.TopLevel);
        string path = AssetDatabase.GetAssetPath(obj[0]) + "/New Lua.txt";
        return path;
    }

创建CraetLuaScriptAsset类,继承EndNameEditAction 重写Action。


using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEditor.ProjectWindowCallback;
using UnityEngine;

class CreateLuaScriptAsset : EndNameEditAction
{
    public override void Action(int instanceId, string pathName, string resourceFile)
    {
        UnityEngine.Object o = CreateScriptAssetFormTemplate(pathName, resourceFile);
        ProjectWindowUtil.ShowCreatedAsset(o);
    }

    internal static UnityEngine.Object CreateScriptAssetFormTemplate(string pathName, string resourcesFile)
    {
        string _fileName = Path.GetFileNameWithoutExtension(pathName);
        pathName = pathName.Replace(_fileName, _fileName + ".lua");
        string fullName = Path.GetFullPath(pathName);
        //读取模板
        StreamReader streamReader = new StreamReader(resourcesFile);
        string text = streamReader.ReadToEnd();
        streamReader.Close();

        //修改内容
        text = Regex.Replace(text, "#SCRIPTNAME#", _fileName);
       
        //写文件
        StreamWriter streamWriter = new StreamWriter(fullName);
        streamWriter.Write(text);
        streamWriter.Close();

        AssetDatabase.ImportAsset(pathName);
        return AssetDatabase.LoadAssetAtPath(pathName, typeof(UnityEngine.Object));
    }

}

在CreatScriptAssetFormTemplate函数中会读取模板内容,按需求修改内容,最后再写入对应路径。这样,就能像创建C#代码一样创建自定义的Lua代码了。

猜你喜欢

转载自blog.csdn.net/qq_33461689/article/details/119248078