[Unity] 腳本模板(四)、File Enum Creator
有時候我們需要根據資料夾下的檔名製作 Enum
尤其是在使用 Plugins 時,並沒有好的測試場景時
會花不少時間把所有功能看完一遍
本篇文章說明了如何製作一個根據檔名快速產生 Enum 的小工具
達到進行快速測試的效果,如以下所示 2DxFX:
Overview
1. 建立模板
2. 建立腳本精靈
3. Editor:根據資料夾下的檔案名稱新增 Enum
4. 檢視自動產生出來的 Enum
5. 測試
1. 建立模板
模板的建立,採用與 Create Script Dialog 官方套件一樣的方法
使用 $ 字號開頭後再進行取代
// <auto-generated /> public enum $EnumName { $Enums }
2. 建立腳本精靈
腳本精靈
基本上就只做字串取代的功能
public class ScriptWizard { private static readonly string m_templetePath = "Assets/Plugins/HotBloodr/Editor/Creator/Templates/"; public static string Create(string name, Dictionary<string, string> replacements) { var path = m_templetePath + name; var script = File.ReadAllText(path); foreach (var pair in replacements) { script = script.Replace(pair.Key, pair.Value); } return script; } }
3. Editor:根據資料夾下的檔案名稱新增 Enum
首先用 OpenFolderPanel 顯示選擇資料夾的視窗
把路徑存下來,再用 Directory.GetFiles
取出資料夾下所有檔案,過濾掉 meta 檔
string path = EditorUtility.OpenFolderPanel("Load...", "", ""); var files = Directory.GetFiles(path).Where(f => !f.EndsWith(".meta")).ToList(); foreach (var file in files) { var fileName = file.Split('/').Last(); fileName = fileName.Split('.').First(); enums += fileName + ",\n\t"; }
以下是完整 Script
4. 檢視自動產生出來的 Enum
// <auto-generated /> public enum Scripts { _2DxFX, _2dxFX_4Gradients, _2dxFX_Additive, _2dxFX_BlackHole, _2dxFX_Blood, _2dxFX_Blur, _2dxFX_BurningFX, _2dxFX_CircleFade, _2dxFX_Clipping, _2dxFX_Color, _2dxFX_ColorChange, _2dxFX_ColorRGB, _2dxFX_CompressionFX, _2dxFX_DesintegrationFX, _2dxFX_DestroyedFX, _2dxFX_Distortion, // ... }
5. 測試
測試方式我是使用鍵盤上下鍵進行切換
這裡用到一個叫 EnumHelper 的小工具
進行 Enum 循訪
using HotBloodr; using UnityEngine; public class Test : MonoBehaviour { private Component m_component = null; private e2DxFX m_2dxfx = e2DxFX._2DxFX; void Update() { if (Input.GetKeyDown(KeyCode.UpArrow)) { if (m_component != null) { UnityEngine.Object.Destroy(m_component); } m_2dxfx = EnumHelper.CircularNext(m_2dxfx); var type = ReflectionHelper.GetType(m_2dxfx.ToString()); m_component = gameObject.AddComponent(type); } } }
Github 完整專案
歡迎您留言與分享!(Welcome for comments or sharing!)
- [Unity] 腳本模板(三)、Singleton ScriptableObject + Asset
- [Shell] Copy File List