天天看點

【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代碼了。