[Unity Script Templates ] 自訂腳本樣板的Keyword

在先前的文章[UNITY SCRIPT TEMPLATES ] 打造專屬的UNITY腳本樣板之中,
有提到如何去自訂 Unity Script Template。

雖然在自動化的流程中已經可以處理掉很多人工coding的作業了,
但還是有稍嫌不足的地方。

本文將會介紹如何讓腳本生成的自動化流程更加完整。

狀況
在撰寫Custom Editor時,都會需要參考到Target Class,
以下方的Template為例,每次建立一個新的Custom Editor都需要去修改圖例中反白的部分。


雖然要更動的部分不多,但是每次都要去修改這種小地方還是覺得麻煩。
( 總之就是還不夠懶 )

像我個人習慣將Custom Editor命名為 Target Class + "Editor",
(ex: MyClass.cs  / MyClassEditor.cs)

所以如果有辦法定義一個關鍵字,並且在腳本生成的時候
將對應的 Editor ClassName 置換掉 "Editor" 這個字串就可以了。

最後找到了 OnWillCreateAsset  去完成這個自動化的流程。


原理
首先我們可以參考一下Unity Script Reference
對於 OnWillCreateAsset 的說明。

當非使用者操作而生成資源時,OnWillCreateAsset 就會被呼叫。
所代入的值就是該檔案的路徑。

有了路徑之後就可以讀取對應的腳本檔案,
並且將設定好的關鍵字置換成我們想要的字串。

接著說明實作的部分,沒時間了快上Code!
/**************************************************
* Description
*   將 Template Keyword 轉換成自定義的字串
* 
* Usage
*   將此腳本放置到任意一個 Editor 資料夾底下
* 
* Keyword
*   #TargetScriptName#  
**************************************************/

using System.IO;
using UnityEditor;
using UnityEngine;

public class CSharpTemplateDetector: UnityEditor.AssetModificationProcessor
{

    // 非使用者操作而產生資源時將會呼叫此函式,eg. ".meta" 檔案
    // 需使用 static 修飾詞
    static void OnWillCreateAsset(string path)
    {
        // 移除.meta extention字串
        path = path.Replace(".meta", "");

        // 檢測路徑的副檔名
        if(Path.GetExtension(path) != ".cs")
        {
            return;
        }

        // 取得腳本路徑
        var index = Application.dataPath.LastIndexOf("Assets");
        path = Application.dataPath.Substring(0, index) + path;

        // 取得腳本名稱
        var fileName = Path.GetFileNameWithoutExtension(path);

        // 轉換關鍵字
        var file = File.ReadAllText(path);
        ReplaceKeyword(fileName, ref file);

        // 覆寫檔案並重新整理資源
        File.WriteAllText(path, file);
        AssetDatabase.Refresh();
    }


    // 轉換關鍵字
    static void ReplaceKeyword(string fileName, ref string script)
    {
        // 將原檔名的 "Editor" 置換為 "" ,再將此字串取代 "#TargetScriptName#"
        script = script.Replace("#TargetScriptName#", fileName.Replace("Editor", ""));
    }

}

順便示範一下成果,下圖是一個自行定義的Script Template,
在這個樣板中使用了 "#TargetScriptName#" Keyword。



從影片可以看到 #TargetScriptName# 在腳本的生成中
自動轉換成對應的Class Name了。



筆記
因為 Unity 的 Script Template 沒辦法參考到其他對象,
因此可以透過自行定義 Keyword,去執行額外的處理。

除了 OnWillCreateAsset ,也可以參考一下 AssetModificationProcessor 所包含的 API。
Unity Script Reference - AssetModificationProcessor

透過這些API來監控資源的狀態變化,並且不侷限在程式腳本上面的話,
一定還有更多可以使用的地方。

參考來源:
Unity Script Template - Keyword Replacer



留言

熱門文章