0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

UnityでGameObjectをSerializedPropertyへ設定する

Posted at

UnityでGameObjectをSerializedPropertyへ設定する

エディタ拡張を書こうとして、SerializeFieldのプロパティを更新する方法を調べたらプリミティブ型のやり方ばかりだったので、オブジェクトでのやり方を書いてみました。
調べながら書いたのでもっとスマートなやり方あったら知りたい。

実際のコード

MyObject.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MyObject : MonoBehaviour {

	[SerializeField]
	private GameObject go;
}
MyEditor.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

[CustomEditor (typeof(MyObject))]
public class MyEditor : Editor {
    public override void OnInspectorGUI ()
    {
        this.serializedObject.Update();

        var serializedPropertyGo = this.serializedObject.FindProperty("go");
        var child = GameObject.Find("Child");

        // GameObjectだからか安直にこうすれば良かった
        serializedPropertyGo.objectReferenceValue = child;
        // 参照するときはキャストすると良し
        // var child = serializedPropertyGo.objectReferenceValue as System.Object as GameObject;

        EditorGUILayout.PropertyField(serializedPropertyGo);

        this.serializedObject.ApplyModifiedProperties();
    }
}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?