Multi-Object Editing

Hey guys!

I’m trying to create a editor script that uses the multi-object editing from Unity, like here http://docs.unity3d.com/Documentation/Manual/Multi-ObjectEditing.html. When I’ve many objects selected with the same component applied to them and with differente values, I’ll have a dash on the field to representate this.

I’ve been using SerializeObject and SerializeField in my script, but looks to be not enough.

Here is a short sample of code of a script with the editor extension that shows how I use SerializeObject and SerializeField.

MonoBehaviour Script:

using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour 
{
    public float Speed = 10.0f;
}

Editor Script:

using UnityEditor;
using UnityEngine;
using System.Collections;

[CustomEditor(typeof(Test)), CanEditMultipleObjects]
public class TestInspector : Editor 
{
    private SerializedObject m_Object;
    private SerializedProperty m_Speed;

    private void OnEnable()
    {
       m_Object = new SerializedObject(target as Test);
       m_Speed = m_Object.FindProperty("Speed");
    }

    public override void OnInspectorGUI()
    {
       m_Object.Update();
       EditorGUILayout.PropertyField(m_Speed);
       m_Object.ApplyModifiedProperties();
    }
}
1 Like

try this instead:

using UnityEditor;
using UnityEngine;
using System.Collections;

[CustomEditor(typeof(Test)), CanEditMultipleObjects]
public class TestInspector : Editor
{
	private SerializedProperty m_Speed;

	private void OnEnable ()
	{
		m_Speed = serializedObject.FindProperty ("Speed");
	}

	public override void OnInspectorGUI ()
	{
		serializedObject.Update ();
		EditorGUILayout.PropertyField (m_Speed);
		serializedObject.ApplyModifiedProperties ();
	}
}

I believe using the “target” object only picks the last selected object as the value to use/display. In other words, don’t create a new SerializedObject based on target, but rather use the builtin serializedObject member.

I guess you could also create a SerializedObject based on “targets” instead, but I don’t see the point when you already have serializedObject as a member.

4 Likes

Both ways worked to me…
Using “targets” instead of “target” and using the builtin serializedObject member…

Thanks Democre!

1 Like

This works:

[CustomEditor(typeof(MyMonoScript)), CanEditMultipleObjects]
public class MyMonoScript_Editor : Editor {

    private MyMonoScript[] myMonoScript;

    private Vector3 startingPoint;

    private void OnEnable() {
        Object[] monoObjects = targets;
        myMonoScript = new MyMonoScript[monoObjects.Length];
        for (int i = 0; i < monoObjects.Length; i++) {
            myMonoScript[i] = monoObjects[i] as MyMonoScript;
        }
    }

    private void OnSceneGUI() {
        for (int i = 0; i < myMonoScript.Length; i++) {
            Debug.Log(myMonoScript[i].transform.position.x);
        }
    }
}
1 Like