三途の川おさかなのブログ

だらだらしている

SerializedObject.FindProperty に文字列でアクセスしたくない

Unity の SerializedObject.FindProperty を使うとき。その対象となるフィールドに文字列でアクセスするのに気持ち悪さを感じていた。

インスペターを拡張するコードの例。

public class Person : MonoBehaviour {
    public int age;
    public int height;
    public int weight;

#if UNITY_EDITOR
    [CustomEditor(typeof(Person))] 
    public class PersonInspector : Editor {
        public override void OnInspectorGUI() {
            this.serializedObject.Update();

            Person personModel = (Person)this.target;
            var spAge = this.serializedObject.FindProperty("age");
            var spHeight = this.serializedObject.FindProperty("height");
            var spWeight = this.serializedObject.FindProperty("weight");

            EditorGUILayout.PropertyField(spAge);
            EditorGUILayout.PropertyField(spHeight);
            EditorGUILayout.PropertyField(spWeight);

            this.serializedObject.ApplyModifiedProperties();
        }
    }
#endif
}

文字列でフィールドを指定してる箇所。

var spAge = this.serializedObject.FindProperty("age");
var spHeight = this.serializedObject.FindProperty("height");
var spWeight = this.serializedObject.FindProperty("weight");

でも nameof 式を使えば文字列を使わずに済んだ。

Person person = null;
var spAge = this.serializedObject.FindProperty(nameof(person.age));
var spHeight = this.serializedObject.FindProperty(nameof(person.height));
var spWeight = this.serializedObject.FindProperty(nameof(person.weight));

nameof 式はコンパイル時に該当箇所を文字列に置き換えてくれるようで、変数に null が入ってても問題無く使える。

参考: nameof 式 - C# リファレンス | Microsoft Docs

nameof 式が使えるのは C#6.0 からなので、Unity5.5 より前だとこの方法は使えなかった。
Unity5.5 より前は C#4.0 相当だ。
それで、ネットに転がってるサンプルコードは文字列で指定してるやつが多いみたい。

参考: Unity 5.5-5.6でC# 6を使う – wizaman's blog