Sort list by distance AND by being active
Hi,
I have a list of game objects that I sort by distance.
_enemyList.Sort(ByDistance);
function ByDistance(a: GameObject, b: GameObject) : int
{
var dstToA = Vector3.Distance(_player.transform.position, a.transform.position);
var dstToB = Vector3.Distance(_player.transform.position, b.transform.position);
return dstToA.CompareTo(dstToB);
}
But what I want to do is to sort them by distance and only if they are active.
Do I then need to call again?
_enemyList.Sort(ByActive);
function ByActive(a: GameObject, b: GameObject) : int
{
var activeA = a.activeSelf;
var activeB = b.activeSelf;
return activeA.CompareTo(activeB);
}
?
Answer by Owen-Reynolds · Feb 26, 2016 at 03:31 PM
You can run a sort twice in a row, and it will work as a double-sort, but not in C# (well, not using C# Sort.) There's a thread on StackOverFlow mocking C# for this.
This is an actual ComSci topic. A Stable sort keeps the order of things that are tied. It's specifically for what you're describing. Sorting by distance, then again by Active, would work if Sort was stable. All the Actives would go to the front, without breaking the sort by distance. But an unstable sort just scrambles everything during each one.
But, you could just write one function to do both:
// all actives to front, regardless if distance:
if(activeA != activeB) return CompareTo(activeA, activeB);
// else both have same active/inactive, use distance:
return CompareTo(distA, distB);
Answer by phil_me_up · Feb 26, 2016 at 01:29 PM
You'll need to implement your own comparison system, and the easiest way is to probably use the IComparable or IComparer interfaces: