テンプレートファイルにカスタムキーワード追加
Unity.app/Contents/Resources/ScriptTemplates
にあるテンプレートファイルに自由にReplaceできるキーワードを追加する
デフォルトでサポートされているのは
key | 説明 |
---|---|
#NAME# | 拡張子なしのファイル名に変換 |
#SCRIPTNAME# | 半角スペース無しで拡張子無しのファイル名に変換 |
#SCRIPTNAME_LOWER# | 半角スペース無しで拡張子無しの全て小文字のファイル名に変換。ただし最初の文字をhoge のように小文字にするとmyHoge となる。 |
こんな風にライセンスを追加(YEARとOWNER)
/* Copyright (C) #YEAR# #OWNER# This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ using UnityEngine; using System.Collections; public class #SCRIPTNAME# : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
文字を入れ替える方法はなんでもいいんだけど、必須なのはOnPostprocessAllAssets
内でAssetDatabase.ImportAsset (path, ImportAssetOptions.ForceUpdate);
を呼び出すこと。
インポート処理を強制的に実行します。(今回はコンパイル処理をキャンセルしたみたいに受け取ってもらえればOK)
そうしないと入れ替えた後のインポート処理がコンパイル後まで待たされてしまうのでコンパイルエラーになる。
using System; using System.IO; using System.Text.RegularExpressions; using UnityEditor; using UnityEngine; public class NamespaceGenerator : UnityEditor.AssetPostprocessor { // ここをいじる static string[] keys = new []{ "YEAR","OWNER", }; static void OnPostprocessAllAssets (string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromPath) { foreach (var path in importedAssets) { if (path.Contains (".cs") || path.Contains (".js") || path.Contains (".boo") || path.Contains (".shader") || path.Contains (".compute")) { for (int i = 0; i < keys.Length; i++) { var key = keys [i]; var text = File.ReadAllText (path); if (text.Contains ("#" + key + "#")) { text = ReplaceText (key, text); StreamWriter writer = new StreamWriter (path, false, new System.Text.UTF8Encoding (true, false)); writer.Write (text); writer.Close (); AssetDatabase.ImportAsset (path, ImportAssetOptions.ForceUpdate); } } } } } // ここをいじる static string ReplaceText (string key, string text) { switch (key) { case "YEAR": // こんな感じでReplace text = Regex.Replace (text, "#" + key + "#", DateTime.Now.Year.ToString()); break; case "OWNER": text = Regex.Replace (text, "#" + key + "#", "Keigo Ando"); break; default: break; } return text; } }