Array.Sort()

Documentation on this function is sparse. I’m using Javascript, and I want to be able to sort an array of myObjects. What is the function that myObject needs to override in order to sort according to my criteria? Inside the function, how do I determine the runtime type of the objects being compared?

freyr described how to use this in http://forum.unity3d.com/viewtopic.php?p=26676

Ok, I’m comparing MonoBehaviours, so I used the second method. Everything compiles except the actual call to Array.Sort(new myComparer()). Unity says:

If I make a new variable of type IComparer and use that, I get:

I switched to ArrayLists instead, and the ArrayList.Sort(IComparable) function works as expected.

I can’t get this to work. I have certainly missed something, but can’t figure out what. :slight_smile:

I get “NullReferenceException : Object reference not set to an instance of an object
System.Collections.ArrayList.Sort(IComparer comparer)”

Many thanks in advance for any help!

import System;
import System.Collections;

//various variables declared here. Have checked and doublechecked names

class QNodeComparer extends IComparer {
  function Compare(x : Object, y: Object) : int {
      return (x.nodeID-y.nodeID);
  }
} 



function Awake() {
	questName = gameObject.name;
	
	questNodeArray = new ArrayList();
	
	var tArray = gameObject.GetComponentsInChildren(QuestNode);
	print(tArray.length);
	for (var tnode : QuestNode in tArray) {
		questNodeArray.Add(tnode);	
	}
	print(questNodeArray.Count);
	questNodeArray.Sort(new QNodeComparer());
	print(questNodeArray[0].nodeID);
	print("arraylist elements: "+questNodeArray.Count);
}

Never mind. The exception was thrown since one of the objects compared didn’t have the variable nodeID set. Oh, well. :slight_smile: