[Unity] 腳本模板(三)、Singleton ScriptableObject + Asset
本篇主要是分享如何自動同時產生 ScriptableObject + Asset
使用 Singleton 代表通常用於各種輕量級的遊戲設定
千萬不要濫用了!
Overview
1. 建立模板
2. 建立腳本精靈
3. EditorWindow
4. 產生 ScriptableObject 檔
5. 產生 Asset
1. 建立模板
模板的建立,採用與 Create Script Dialog 官方套件一樣的方法
使用 $ 字號開頭後再進行取代
using UnityEngine; public class $ClassName : ScriptableObject { #region Singleton public static $ClassName Instance { get { if (instance == null) { instance = Resources.Load<$ClassName>("$AssetPath"); } return instance; } } protected static $ClassName instance; #endregion }
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. EditorWindow
EditorWindow 的製作就不詳加贅述了
簡單來說就是設定 ScriptableObject 和 Asset 的位置
以及名稱要叫什麼
void OnGUI() { // ... m_scriptPath = CreateField("Script Path", m_scriptPath, style); m_assetPath = CreateField("Asset Path", m_assetPath, style); m_name = CreateField("Name", m_name, style); if (GUILayout.Button("Create Asset")) { CreateScriptableObject(); } // ... }
4. 產生 ScriptableObject 檔
這裡直接新增一個 Dictionary
塞給剛剛的 ScriptWizard 做完字串替換後存檔
再呼叫 AssetDatabase.Refresh()
主要是要等待 Unity Compile 結束才有辦法建立 Asset
var replacements = new Dictionary<string, string>() { { "$ClassName", m_name }, { "$AssetPath", assetPath }, }; var fileString = ScriptWizard.Create(m_templateName, replacements); File.WriteAllText(file, fileString, Encoding.UTF8); AssetDatabase.Refresh();
5. 產生 Asset
最後我們在 Update 裡判斷 Unity Compile 完了沒
結束的話就可以產生 Asset 啦!
void Update() { if (!EditorApplication.isCompiling) { if (m_isNeedCreate) { CreateAsset(); m_isNeedCreate = false; } if (m_isNeedFocus) { EditorUtility.FocusProjectWindow(); Selection.activeObject = m_selection; m_isNeedFocus = false; } } }
Github 完整專案
歡迎您留言與分享!(Welcome for comments or sharing!)
- [Unity] 腳本模板(二)、Script Create Dialog
- [Unity] 腳本模板(四)、File Enum Creator