1. 程式人生 > >unity之定製指令碼模板

unity之定製指令碼模板

1、unity的指令碼模板

       新版本unity中的C#指令碼有三類,第一類是我們平時開發用的C# Script;第二類是Testing,用來做單元測試;第三類是Playables,用作TimeLine中管理時間線上每一幀的動畫、聲音等。我們點選建立指令碼時,會自動生成unity內建的一套模板:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour {

    
// Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
如果我們開發時使用的框架有明顯的一套基礎模板, 那為專案框架定製一套模板會很有意義,這樣可以為我們省去編寫重複程式碼的時間。這裡介紹兩種方法。  

2、修改預設指令碼模板

    開啟unity安裝目錄,比如D:\unity2018\Editor\Data\Resources\ScriptTemplates,unity內建的模板指令碼都在這裡,那麼可以直接修改這裡的cs檔案,比如我們將81-C# Script-NewBehaviourScript.cs.txt檔案修改為如下,那下次建立C# Script時模板就會變成這樣:

 

////////////////////////////////////////////////////////////////////
//                          _ooOoo_                               //
//                         o8888888o                              //
//                         88" . "88                              //
//                         (| ^_^ |)                              //
//                         O\  =  /O                              
// // ____/`---'\____ // // .' \\| |// `. // // / \\||| : |||// \ // // / _||||| -:- |||||- \ // // | | \\\ - /// | | // // | \_| ''\---/'' | | // // \ .-\__ `-` ___/-. / // // ___`. .' /--.--\ `. . ___ // // ."" '< `.___\_<|>_/___.' >'"". // // | | : `- \`.;`\ _ /`;.`/ - ` : | | // // \ \ `-. \_ __\ /__ _/ .-` / / // // ========`-.____`-.___\_____/___.-`____.-'======== // // `=---=' // // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // // 佛祖保佑 永不宕機 永無BUG // //////////////////////////////////////////////////////////////////// using System.Collections; using System.Collections.Generic; using UnityEngine; public class #SCRIPTNAME# : MonoBehaviour { // Use this for initialization void Start () { #NOTRIM# } // Update is called once per frame void Update () { #NOTRIM# } }
 

3、拓展指令碼模板

      上面講的第一種方法直接修改了unity的預設配置,這並不適應於所有專案,這裡第二種方法會更有效,可以針對不同的專案和框架建立合適的指令碼模板。        首先,先建立一個文字檔案MyTemplateScript.cs.txt作為指令碼模板,並將其放入unity project的Editor資料夾下,模板程式碼為:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MyNewBehaviourScript : MonoBase {

    //新增事件監聽
    protected override void AddMsgListener()
    {

    }
    
    //處理訊息
    protected override void HandleMsg(MsgBase msg)
    {
        switch (msg.id)
        {
            default:
                break;
        }
    }

}
    我們使用時,需要在Project檢視中右擊->Create->C# FrameScript 建立指令碼模板,因此首先要建立路徑為Assets/Create/C# FrameScript的MenuItem,點選建立指令碼後,需要修改指令碼名字,因此需要在拓展編輯器指令碼中繼承EndNameEditAction來監聽回撥,最終實現輸入指令碼名字後自動建立相應的指令碼模板。

程式碼如下,將這個指令碼放入Editor資料夾中:

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

public class CreateTemplateScript {

    //指令碼模板路徑
    private const string TemplateScriptPath = "Assets/Editor/MyTemplateScript.cs.txt";

    //選單項
    [MenuItem("Assets/Create/C# FrameScript", false, 1)]
    static void CreateScript()
    {
        string path = "Assets";
        foreach (UnityEngine.Object item in Selection.GetFiltered(typeof(UnityEngine.Object),SelectionMode.Assets))
        {
            path = AssetDatabase.GetAssetPath(item);
            if (!string.IsNullOrEmpty(path) && File.Exists(path))
            {
                path = Path.GetDirectoryName(path);
                break;
            }
        }
        ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance<CreateScriptAsset>(),
        path + "/MyNewBehaviourScript.cs",
        null, TemplateScriptPath);

    }
    
}


class CreateScriptAsset : EndNameEditAction
{
    public override void Action(int instanceId, string newScriptPath, string templatePath)
    {
        UnityEngine.Object obj= CreateTemplateScriptAsset(newScriptPath, templatePath);
        ProjectWindowUtil.ShowCreatedAsset(obj);
    }

    public static UnityEngine.Object CreateTemplateScriptAsset(string newScriptPath, string templatePath)
    {
        string fullPath = Path.GetFullPath(newScriptPath);
        StreamReader streamReader = new StreamReader(templatePath);
        string text = streamReader.ReadToEnd();
        streamReader.Close();
        string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(newScriptPath);
        //替換模板的檔名
        text = Regex.Replace(text, "MyTemplateScript", 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(newScriptPath);
        return AssetDatabase.LoadAssetAtPath(newScriptPath, typeof(UnityEngine.Object));
    }

}
然後,在project中,點選建立C# FrameScript,輸入指令碼名字,對應的指令碼就已經建立好了

4、總結

     上面介紹了兩種方案,第一種適合玩玩,第二種方法顯然逼格高一些,為不同的專案和框架定製一套指令碼模板,可以讓我們少寫一些重複程式碼。按照上面介紹的方法,我們同樣可以修改和拓展Testing、Playables的指令碼模板,甚至shader,我們也可以定製模板。