Search Unity

How to access the values of SerializedProperty.hasMultipleValue ?

Discussion in 'Immediate Mode GUI (IMGUI)' started by LazloBonin, Jun 25, 2015.

  1. LazloBonin

    LazloBonin

    Joined:
    Mar 6, 2015
    Posts:
    813
    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?
     
  2. Neyl

    Neyl

    Joined:
    Feb 3, 2011
    Posts:
    18
    For iterating over each property and getting their values you can do something like this (theoretically)
    Code (CSharp):
    1. Object[] allTargetObjects = myProperty.serializedObject.targetObjects;
    2. foreach(var targetObject in allTargetObjects)
    3. {
    4.     SerializedObject iteratedObject = new SerializedObject(targetObject);
    5.     SerializedProperty iteratedProperty = iteratedObject.FindProperty(myProperty.propertyPath);
    6.     float iteratedValue = iteratedProperty.floatValue;//get any value
    7. }
     
    alfish, Flying_Banana and LazloBonin like this.
  3. LazloBonin

    LazloBonin

    Joined:
    Mar 6, 2015
    Posts:
    813
    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:

    Code (CSharp):
    1. public static IEnumerable<SerializedProperty> Multiple(this SerializedProperty property)
    2. {
    3.     if (property.hasMultipleDifferentValues)
    4.     {
    5.         return property.serializedObject.targetObjects.Select(o => new SerializedObject(o).FindProperty(property.propertyPath));
    6.     }
    7.     else
    8.     {
    9.         return new[] { property };
    10.     }
    11. }
    12.  
    Now you can call:

    Code (csharp):
    1. foreach (SerializedProperty iteratedProperty in myProperty.Multiple())
    2. {
    3.        iteratedProperty.floatValue = ...
    4. }
    The extension method requires System.Linq and will automatically handle non-multiple-values properties, so it's safe to use in any context.
     
    shelim and Flying_Banana like this.