- Home /
Incrementing a SerializedProperty on a per-object basis
Understanding that using Editor.targets
is becoming more and more difficult as a result of Editor.SetDirty()
becoming more or less unusable, I'm looking to the "correct" solution to the following problem.
I create a component (ExampleComponent) with an integer variable (exampleInt). I want to create a CustomEditor that has displays a button that increases the exampleInt by one on a per-object basis. (Essentially ++exampleInt.)
What I don't understand is how to do this correctly using the "new and improved" Editor.serializedObject. As I understand it, SerializedObject.targetObjects returns a read-only list of the target objects, and thus is not intended to be edited? And as far as I can tell there's no way of getting/setting the individual values of SerializedProperty either?
So one following solution would be:
if (intProp.has$$anonymous$$ultipleDifferentValues)
{
EditorGUI.show$$anonymous$$ixedValue = true;
foreach (UnityEngine.Object o in intProp.serializedObject.targetObjects)
{
SerializedObject so = new SerializedObject(o);
so.Update();
SerializedProperty so_intProp = so.FindProperty(intProp.name);
so_intProp.intValue += 1;
so.Apply$$anonymous$$odifiedProperties();
}
}
Isn't that essentially breaking the concept of the targetObjects being read-only, and a weird workaround to a simple problem?
Answer by dCalle · Jun 10, 2017 at 10:33 AM
You can set values of a serialized property.
Either by using EditorGUILayout.PropertyField or,
if you know which field of an object you want to change you can use serializedProperty.objectReferenceValue = ObjectField(serializedProperty.objectReferenceValue) (as for GameObjects and ScriptableObjects).
The only Pain in the Ass right now is, to figure out with what Type you are dealing with right now, when using the Iterator given by the serializedObject.GetIterator() of your Editor.
Remember though, that you need to use serializedObject.ApplyModifiedProperties() command of your Editor to apply changes.