Sorting Arrays results in weird error

When trying to sort an array of GameObjects with Array.Sort I get this:

InvalidOperationException: No IComparable or IComparable interface found.
System.Array.compare[Object] (System.Object value1, System.Object value2, IComparer1 comparer) (at /Applications/buildAgent/work/b59ae78cff80e584/mcs/class/corlib/System/Array.cs:1755) System.Array.qsort[Object,Object] (System.Object[] keys, System.Object[] items, Int32 low0, Int32 high0, IComparer1 comparer) (at /Applications/buildAgent/work/b59ae78cff80e584/mcs/class/corlib/System/Array.cs:1721)
System.Array.Sort[Object,Object] (System.Object keys, System.Object items, Int32 index, Int32 length, IComparer1 comparer) (at /Applications/buildAgent/work/b59ae78cff80e584/mcs/class/corlib/System/Array.cs:1674) Rethrow as InvalidOperationException: The comparer threw an exception. System.Array.Sort[Object,Object] (System.Object[] keys, System.Object[] items, Int32 index, Int32 length, IComparer1 comparer) (at /Applications/buildAgent/work/b59ae78cff80e584/mcs/class/corlib/System/Array.cs:1677)
System.Array.Sort[Object] (System.Object array, Int32 index, Int32 length) (at /Applications/buildAgent/work/b59ae78cff80e584/mcs/class/corlib/System/Array.cs:1608)
System.Collections.ArrayList.Sort () (at /Applications/buildAgent/work/b59ae78cff80e584/mcs/class/corlib/System.Collections/ArrayList.cs:3185)
UnityScript.Lang.Array.Sort ()
EnemyMoveScript.Start () (at Assets/Scripts/EnemyMoveScript.js:11)

Post your code, not just the error.

1 Answer

1

Firstly - don’t use Array use List or a native array (see this)

Secondly - how are you expecting them to sort anyway? You need to be able to specify the sort order:

    var list : List.<GameObject>;
    ...
    list.Sort( function(gameObject1, gameObject2) return 0); //Actually return 0, 1 or -1 depending on the sort order you want
    list.Sort( function(gameObject1, gameObject2) return gameObject1.transform.x > gameObject2.transform.x ? 1 : -1); //Example

You can put a whole function in there with { and } if you need to.

All I want to do is sort them alphabetically and dont want to stray from Unity stuff. Using that list just instantly throws me errors.

You aren't straying from Unity! If you are using Array then you are currently using an outdated, slow and error prone way of storing arrays that you should not use. As I said, you can use a native array if you wish (perhaps you are?) - but in any case to sort them you need to provide a comparer. something.Sort(function(go1, go2) return String.Compare(go1.name, go2.name));

Here's the wiki entry http://wiki.unity3d.com/index.php?title=Which_Kind_Of_Array_Or_Collection_Should_I_Use?