【Unity】既存のEditor拡張を乗っ取って自分のEditor拡張を使う【Editor拡張】
はじめに
いろいろなアセットを使っていると便利なことにEditor拡張がついてきて使いやすい!!
けど、個人的にもうちょい足したい…が手を入れるとアセットの更新があったときに毎回マージするのはしんどい…
Editor拡張の拡張って書けるのかな
— てんちょー / 筑野(ちくの)えり💕 (@shop_0761) February 4, 2019
Editor拡張の拡張は出来なかったんですが、乗っ取ることはできたので今回はその話をします。
やりかた
Editor拡張を用意する
なんか書きます。
using UnityEngine; public class Test : MonoBehaviour { [HideInInspector] public string str = "こんにちは"; public void Message() { Debug.Log("メッセージだよ: " + str); } }
using UnityEditor; using UnityEngine; [CustomEditor(typeof(Test))] public class TestEditor : Editor { public override void OnInspectorGUI() { base.OnInspectorGUI(); var test = target as Test; if (GUILayout.Button("メッセージをよむ")) { test.Message(); } } }
ボタンが出るようになるので、押すとログが出ます。
上書きしたいEditor拡張を書く
今回のメインはここ。とっても邪法です。
以下は推測です。
- [CustomEditor(typeof(Hogehoge))] のtypeof で指定したクラスには一つのEditor拡張しか使えない
- Editor拡張用のクラスを探すのは辞書順
だと思われます。これを逆手に取ります。
今回の場合は 辞書順にソートしたとき、 TestEditor.cs より早い名前にしてあげれば良さそうです。一文字削ってTestEdito.cs でもよいです。
using UnityEditor; using UnityEngine; [CustomEditor(typeof(Test))] public class TestEdito : Editor { public override void OnInspectorGUI() { base.OnInspectorGUI(); var test = target as Test; if (GUILayout.Button("メッセージをよむぞ")) { test.Message(); } } }
できた~~~~~~~
拡張メソッドを書く
まあこれだとpublicな関数がたたけるくらいで、はい なるほど ってなって終わりなんですが
拡張メソッドも一緒に使うと便利です。
using UnityEngine; public static class TestExtension { public static void MessageExtention(this Test test) { test.str = "やあ " + test.str; Debug.Log("おりゃ 上書きしてあるぞい!: " + test.str); } }
そして、上書きしたほうのEditor拡張である TestEdito.csには
using UnityEditor; using UnityEngine; [CustomEditor(typeof(Test))] public class TestEdito : Editor { public override void OnInspectorGUI() { base.OnInspectorGUI(); var test = target as Test; if (GUILayout.Button("メッセージをよむぞ")) { test.MessageExtention(); //拡張メソッド } } }
ということができます。
まとめ
なるべくよそのアセットには手を入れたくないけど、便利につかいたい…もうちょいEditor拡張したい…
ときに便利です。Editor拡張を _.cs とかにされたらどうするんだろ…
だれが使うんだろ。おわり。