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?
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.
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.
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.
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.
private static void Swap(SerializedProperty list, int x, int y)
{
if (x == y) return;
if (x > y) (x, y) = (y, x);
list.MoveArrayElement(x, y);
if (y - x != 0) list.MoveArrayElement(y - 1, x);
}
I finally came to insertion sort because MoveArrayElement() actually do the same thing as nested loop of a classic insertion sort algorithm. Here is my helper class which wraps SerializedProperty array with elements of T. It expects elemet getter and optional IComparer. I’ve stolen implementation from ArrayHelper.Sort() which is part of .net SDK and adopted it for MoveArrayElement(). ArrayHelper.Sort() sorts using different strategies depending on array size, but I think insertion sort will be the most effective for SerializedProperty because it doesn’t allow direct assignment:
public class SerializedPropertyArrayHelper<T>
{
private SerializedProperty _property;
private Func<SerializedProperty, int, T> _getItemValue;
private IComparer<T> _comparer;
public SerializedPropertyArrayHelper ( SerializedProperty property, Func<SerializedProperty, int, T> getItemValue )
: this( property, null, getItemValue )
{
}
public SerializedPropertyArrayHelper ( SerializedProperty property,
IComparer<T> comparer, Func<SerializedProperty, int, T> getItemValue )
{
_property = property;
_comparer = comparer ?? Comparer<T>.Default;
_getItemValue = getItemValue;
}
public void Sort ()
{
var size = _property.arraySize;
if( size < 2 )
return;
InsertionSort( 0, size - 1 );
}
private void InsertionSort ( int lo, int hi )
{
int i, j;
T t;
for( i = lo; i < hi; i++ )
{
j = i;
t = _getItemValue( _property, i + 1 );
while( j >= lo && _comparer.Compare( t, _getItemValue( _property, j ) ) < 0 )
{
j--;
}
if( i != j )
_property.MoveArrayElement( i + 1, j + 1 );
}
}
}
Here is an example of array item type:
[Serializable]
internal class TimeEvent
{
public double Time;
public QuickEvent Event;
}
Editor implements OnEnable() to make helper:
private void OnEnable ()
{
var so = serializedObject;
_player = so.FindProperty( nameof( VideoPlayerEvents.Player ) );
_events = so.FindProperty( nameof( VideoPlayerEvents.Events ) );
_eventsHelper = new SerializedPropertyArrayHelper<double>(
_events, ( p, i ) =>
{
var item = p.GetArrayElementAtIndex( i );
// Move iterator to Time property is safe to use because GetArrayElementAtIndex() copies property internally
item.NextVisible( true );
return item.doubleValue;
} );
}
Somewhere in OnInspectorGUI():
if( GUILayout.Button( "Sort" ) )
{
_eventsHelper.Sort();
}
Here’s an alternative version which uses extension methods + some added exceptions. It can be used the same way as List.Sort(comparer)
public static class SerializedPropertyExtensions
{
private sealed class FunctorComparer<T> : IComparer<T>
{
Comparison<T> _comparison;
public FunctorComparer(Comparison<T> comparison)
{
_comparison = comparison;
}
public int Compare(T x, T y)
{
return _comparison(x, y);
}
}
public static void SortArray(this SerializedProperty property, int index, int count, Comparison<SerializedProperty> comparison)
{
var comparer = new FunctorComparer<SerializedProperty>(comparison);
SortArray(property, index, count, comparer);
}
public static void SortArray(this SerializedProperty property, Comparison<SerializedProperty> comparison)
{
var comparer = new FunctorComparer<SerializedProperty>(comparison);
SortArray(property, 0, property.arraySize, comparer);
}
public static void SortArray(this SerializedProperty property, IComparer<SerializedProperty> comparer)
{
SortArray(property, 0, property.arraySize, comparer);
}
public static void SortArray(this SerializedProperty property, int index, int count, IComparer<SerializedProperty> comparer)
{
if (!property.isArray)
throw new ArgumentException("Property is not an array", nameof(property));
if (index < 0)
throw new ArgumentException("Index is out of range.", nameof(index));
int hi = index + count - 1;
if (hi >= property.arraySize)
throw new ArgumentException("Arguments index and count reach outside of the array range.");
if (property.arraySize <= 1)
return;
for (int i = index; i < hi; i++)
{
int j = i;
SerializedProperty itemA = property.GetArrayElementAtIndex(i + 1);
while (j >= index && comparer.Compare(itemA, property.GetArrayElementAtIndex(j)) < 0)
{
j--;
}
if (i != j)
property.MoveArrayElement(i + 1, j + 1);
}
}
}
I took a proper look at this problem and figured out that I wanted a solution that:
- Only read each element once
- Only moved elements that were strictly required to move
I spent days researching this, and found the necessary pieces.
- Find a ‘Longest increasing subsequence’, and treat those elements as stationary.
- A way to track the positions of elements in a list while the ‘MoveArrayElement’ is working on it, without revisiting all the elements. This turned out to be a Fenwick tree.
I did many performance tests, and my algorithm is actually faster than clearing the array and reinserting every element in the correct order (up to 512 elements, where it starts to fall behind).
That being said… just sorting the array in c# and calling Update() is 10x faster on tiny arrays, and upwards of 1000x faster on arrays larger than a few thousand elements.
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
public static class SerializedPropertyExtension {
public static void SortArray (this SerializedProperty arrayProperty) {
switch (arrayProperty.arrayElementType) {
case "int": arrayProperty.SortArray(p => p.intValue ); break;
case "long": arrayProperty.SortArray(p => p.longValue ); break;
case "byte": arrayProperty.SortArray(p => (byte) p.intValue ); break;
case "sbyte": arrayProperty.SortArray(p => (sbyte) p.intValue ); break;
case "short": arrayProperty.SortArray(p => (short) p.intValue ); break;
case "ushort": arrayProperty.SortArray(p => (ushort)p.intValue ); break;
case "uint": arrayProperty.SortArray(p => p.uintValue ); break;
case "ulong": arrayProperty.SortArray(p => p.ulongValue ); break;
case "float": arrayProperty.SortArray(p => p.floatValue ); break;
case "double": arrayProperty.SortArray(p => p.doubleValue ); break;
case "bool": arrayProperty.SortArray(p => p.boolValue ); break;
case "string": arrayProperty.SortArray(p => p.stringValue ); break;
case "char": arrayProperty.SortArray(p => (char) p.intValue ); break;
case "Enum": arrayProperty.SortArray(p => p.enumValueIndex); break;
case var s when s.StartsWith("PPtr<$"):
arrayProperty.SortArray(p => p.objectReferenceValue?.name ?? string.Empty);
break;
default:
Debug.LogWarning($"SortArray: no default sort defined for arrayElementType '{arrayProperty.arrayElementType}'. Provide a converter explicitly.");
break;
}
}
public static void SortArray<T> (this SerializedProperty arrayProperty, System.Converter<SerializedProperty, T> converter) {
SortArray<T>( arrayProperty, converter, Comparer<T>.Default.Compare );
}
public static void SortArray<T> (this SerializedProperty arrayProperty, System.Converter<SerializedProperty, T> converter, System.Comparison<T> comparison = null, bool skipLisOptimization = false) { // The LIS optimization uses 85% more memory, but runs 8% faster
if ( arrayProperty == null ) throw new System.ArgumentNullException(nameof(arrayProperty));
if ( !arrayProperty.isArray ) throw new System.ArgumentException($"Calling SortArray on the property {arrayProperty.propertyPath}, which is not an array, but a {arrayProperty.propertyType}!", nameof(arrayProperty));
if ( comparison == null ) throw new System.ArgumentNullException(nameof(comparison));
var arraySize = arrayProperty.arraySize;
if (arraySize <= 1) return;
var elements = new T[arraySize];
var arrayElement = arrayProperty.GetArrayElementAtIndex(0);
for (int i = 0; i < arraySize; i++) {
elements[i] = converter( arrayElement );
arrayElement.Next(false);
}
var positions = new int[arraySize];
var targetPositions = new int[arraySize];
for (int i = 0; i < arraySize; i++)
positions[i] = i;
System.Array.Sort( elements, positions, 0, arraySize, Comparer<T>.Create( comparison ) );
for (int i = 0; i < arraySize; i++)
targetPositions[positions[i]] = i;
// FenwickTree:
// the non-zero content in the tree represents items, the sums
// in the tree can be used to locate current indexes after move operations
// Ex: a list of 5 items: [1, 1, 1, 1, 1, 0]
// The final number is for elements that
// are moved to the end. We apply the rule that
// items are inserted at the start of the bucket,
// except the last, where we don't know.
//
// Incrementing a number costs log(n) time.
// Summing a range costs *just* log(n) time as well.
//
var buckets = new FenwickTree(
Enumerable.Repeat(1, arraySize).Append(0),
arraySize + 1);
// LIS - longest increasing subsequence
int[] lisValues;
int[] lisSourceIndexes;
int[] listPredecessors;
int numLisElements = 0;
int [] onlyLis = null; // An array of only the non-moving elements
bool[] lis = null;
if (!skipLisOptimization) {
// LIS - Longest Increasing Subsequence... these elements will in theory not need
// to be moved anywhere, but then we need to find them first
lisValues = new int[arraySize];
lisSourceIndexes = new int[arraySize];
listPredecessors = new int[arraySize];
numLisElements = 1;
lisValues [0] = targetPositions[0];
lisSourceIndexes[0] = 0;
listPredecessors[0] = -1;
for (int i = 1; i < arraySize; i++)
{
var v = targetPositions[i];
var lisIndex = ~System.Array.BinarySearch(lisValues, 0, numLisElements, v);
listPredecessors[i] = lisIndex == 0 ? -1 : lisSourceIndexes[lisIndex - 1];
lisValues [lisIndex] = v;
lisSourceIndexes[lisIndex] = i;
if (lisIndex == numLisElements)
numLisElements++;
}
var tailIndex = lisSourceIndexes[numLisElements - 1];
onlyLis = new int [numLisElements];
lis = new bool[arraySize];
for (int i = tailIndex, lis_i = numLisElements - 1; i != -1; i = listPredecessors[i], lis_i--) {
onlyLis[lis_i] = targetPositions[i];
lis[i] = true;
}
}
for (int i = 0; i < arraySize; i++) {
if (skipLisOptimization || !lis[positions[i]]) {
// Moving element to 'i', so get the i'th smallest element
var originalIndexToMove = positions[i];
var upToDateIndexToMove = buckets.Sum(originalIndexToMove)-1;
buckets.Update(originalIndexToMove, -1);
int realTarget;
if (skipLisOptimization) { // just move everything to the beginning
realTarget = i;
buckets.Update(0, 1);
}
else {
// Move this movable element to where the first non-movable (LIS), larger element is.
var lisAnchorPosition = ~System.Array.BinarySearch( onlyLis, 0, numLisElements, targetPositions[positions[i]] );
if (lisAnchorPosition == numLisElements) {
// to the end
buckets.Update(arraySize, 1);
realTarget = arraySize - 1;
}
else {
var bucket = positions[onlyLis[lisAnchorPosition]];
realTarget = buckets.Sum(bucket)-1;
buckets.Update(bucket, 1);
}
}
arrayProperty.MoveArrayElement(upToDateIndexToMove, realTarget);
}
}
}
}
// Fenwick trees are used to compute range aggregates in log(n) time.
// An update of any value in the range takes log(n) time too.
//
// https://algocademy.com/blog/implementing-fenwick-trees-for-efficient-range-queries/
public class FenwickTree {
private int[] tree;
public FenwickTree (int size) {
tree = new int[size+1];
}
public FenwickTree (IEnumerable<int> source, int count) : this( count ) {
if (tree.Length > 1) {
{
int i = 1;
foreach (var e in source)
tree[i++] = e;
}
for (int i = 1; i < tree.Length; i++) {
var p = i + (i & (-i));
if (p < tree.Length)
tree[p] += tree[i];
}
}
}
public void Update (int i, int delta) {
i++; // simulate 0-indexed array
while (i < tree.Length) {
tree[i] += delta;
i += i & (-i); // Add the least significant bit
}
}
//public int[] ToArray () {
// var result = new int[tree.Length-1];
// var sum = 0;
// for (int i = 1; i < tree.Length; i++) {
// var nextSum = Sum(i-1);
// result[i-1] = nextSum - sum;
// sum = nextSum;
// }
// return result;
//}
// Get sum of range [0, i]
public int Sum (int i) {
i++;
int result = 0;
while (i > 0) {
result += tree[i];
i -= i & (-i); // Remove the least significant bit
}
return result;
}
// Get sum of range [left, right]
public int Sum (int left, int right) {
return Sum(right) - Sum(left - 1);
}
};