【Unity】【エディタ拡張】自作クラス型のSerializedPropertyに値をセットする

自作クラス型のSerializedPropertyに値をセットする方法です。

Unity2018.4.0

やりたいこと

Unityでエディタ拡張をする時にはSerializedPropertyを通してフィールドの値を更新します。

var prop = serializedObject.FindProperty("_property");
prop.intValue = 1;

これらはプリミティブ型だけでなく、Unityの基本的な構造体に対応しています。

var prop = serializedObject.FindProperty("_property");
prop.animationCurveValue = AnimationCurve.Linear(0, 0, 1, 1);

これに対して自作のクラスや構造体はこの方法では値を更新できないので、違う方法で実現します。

実現方法

これを実現する便利なクラスを作ってくれている方がいたので、今回はこれを使ってみます。

answers.unity.com

これを使って、以下のようなソースコードを記述します。

using UnityEngine;
using Supyrb;
#if UNITY_EDITOR
using UnityEditor;
#endif

public class Example : MonoBehaviour
{
    [System.Serializable]
    public class SomeClass
    {
        public int someInt;
    }

    [SerializeField]
    private SomeClass _someClass;
}

#if UNITY_EDITOR
[CustomEditor(typeof(Example))]
public class ExampleEditor : Editor
{
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();

        if (GUILayout.Button("Set Object"))
        {
            var someClassProp = serializedObject.FindProperty("_someClass");
            
            // インスタンスをSerializedPropertyに変換
            someClassProp.SetValue(new Example.SomeClass{ someInt = Random.Range(0, 100)});
            
            // SerializedPropertyからインスタンスを取得
            var obj = someClassProp.GetValue<Example.SomeClass>();
        }
    }
}
#endif

SomeClass型のSerializedPropertyを通して値を更新しています。

結果

結果はこんな感じです。

f:id:halya_11:20190620013121g:plain

自作クラス型のSerializedPropertyに値をセットできていることを確認できました。