I know I can use SerializedProperty.hasMultipleValue to determine whether I’m in multi-object editing mode. However, I see no way of iterating over each of the values or even simply getting / setting them.
(How) can I do it?
I know I can use SerializedProperty.hasMultipleValue to determine whether I’m in multi-object editing mode. However, I see no way of iterating over each of the values or even simply getting / setting them.
(How) can I do it?
For iterating over each property and getting their values you can do something like this (theoretically)
Object[] allTargetObjects = myProperty.serializedObject.targetObjects;
foreach(var targetObject in allTargetObjects)
{
SerializedObject iteratedObject = new SerializedObject(targetObject);
SerializedProperty iteratedProperty = iteratedObject.FindProperty(myProperty.propertyPath);
float iteratedValue = iteratedProperty.floatValue;//get any value
}
Awesome! I thought of trying that but didn’t know you could call a constructor on SerializedObject.
I turned it into an extension method, if anybody’s interested:
public static IEnumerable<SerializedProperty> Multiple(this SerializedProperty property)
{
if (property.hasMultipleDifferentValues)
{
return property.serializedObject.targetObjects.Select(o => new SerializedObject(o).FindProperty(property.propertyPath));
}
else
{
return new[] { property };
}
}
Now you can call:
foreach (SerializedProperty iteratedProperty in myProperty.Multiple())
{
iteratedProperty.floatValue = ...
}
The extension method requires System.Linq and will automatically handle non-multiple-values properties, so it’s safe to use in any context.