Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Sorting an Array within a SerializedProperty

Discussion in 'Editor & General Support' started by Democide, Nov 6, 2015.

  1. Democide

    Democide

    Joined:
    Jan 29, 2013
    Posts:
    315
    So, I've hit that speedbump: How can I sort an array that I have only within a SerializedProperty? Granted, I could cast it to the proper array and then sort it but I kinda want to avoid that. Any ideas?
     
  2. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,195
    You could implement sort as normal, by using GetArrayElementAtIndex to compare the objects and MoveArrayElement to swap in-place. Implenting QuickSort or whatever based on that should be trivial.

    Casting to the proper array and doing an Array.Sort sounds a lot easier, though, and built-in sorts are very well optimized.
     
    aka3eka likes this.
  3. Democide

    Democide

    Joined:
    Jan 29, 2013
    Posts:
    315
    Hm. Is there a way to make that undoable then? Also casting the SerializedProperty to a List gives me the "type is not a supported pptr value" error.
     
    Last edited: Nov 6, 2015
  4. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,195
    Yeah, the SerializedProperty is not the array, it's a wrapper around the array. I'm pretty sure the array (or List if that's what you're using) is hiding in the .objectReferenceValue of the serializedProperty.

    You'll have to check if calling ApplyModifiedProperties on the SerializedObject (as you're already doing, right?) enables you to Undo the operation. If not, you'll have to register an Undo yourself, through the Undo class.
     
  5. Leonidas001

    Leonidas001

    Joined:
    Apr 23, 2018
    Posts:
    2
    Bit of a thread necro but in case anyone else finds this - MoveArrayElement does not swap-in-place but instead removes the element at the source index and inserts it at the destination index. Had me scratching my head for a while.
     
    aka3eka, rythianns and SudoCat like this.
  6. fedorenkosergiy

    fedorenkosergiy

    Joined:
    Jun 11, 2014
    Posts:
    8
    Code (CSharp):
    1. private static void Swap(SerializedProperty list, int x, int y)
    2.         {
    3.             if (x == y) return;
    4.  
    5.             if (x > y) (x, y) = (y, x);
    6.  
    7.             list.MoveArrayElement(x, y);
    8.  
    9.             if (y - x != 0) list.MoveArrayElement(y - 1, x);
    10.         }