Sorting a List of objects with CompareTo
Hello, everyone! My issue is, when I'm trying to Sort a List of RaycastHit2D's with CompareTo method it doesn't work. Here's the code part:
RaycastHit2D[] hits = Physics2D.BoxCastAll (caststart, playersize, 0f, castdir, c5_maxrange);
List<RaycastHit2D> hitList = new List<RaycastHit2D> ();
hitList.AddRange (hits);
Debug.Log ("Objects withOUT sorting");
foreach (RaycastHit2D hit in hitList){
Debug.Log (hit.collider.name + " " + hit.collider.bounds.max.x);
}
// return;
hitList.Sort(delegate(RaycastHit2D x, RaycastHit2D y) {
return(x.collider.bounds.max.x.CompareTo(y.collider.bounds.max.x));
});
Debug.Log ("Sorted Objects");
foreach (RaycastHit2D hit in hits){
Debug.Log (hit.collider.name + " " + hit.collider.bounds.max.x);
}
And, unfortunately for me, the result before and after sorting doesn't change. The reason I need this sorting is that BoxCastAll catches upper colliders first. then the lower ones, and when I start to check members in the list in reverse order I would like to check upper collider's first. But basically, I'm trying to understand why Sort doesn't actually sort. Thank you for the answer in advance.
Answer by N2-alex · Jul 09, 2017 at 06:23 PM
Update.
Tried Using.System.Linq and after some struggling it worked! But only when OrderBy to a new list, which then cannot be sorted. Here's the code in case somebody faces the same issue:
RaycastHit2D[] hits = Physics2D.BoxCastAll (caststart, playersize, 0f, castdir, c5_maxrange);
List<RaycastHit2D> hitList = hits.OrderBy(b=>b.collider.bounds.max.x).ThenBy(b=>b.collider.bounds.max.y).ToList();
Debug.Log ("Sorted Objects");
foreach (RaycastHit2D hit in hitList){
Debug.Log (hit.collider.name + " " + hit.collider.bounds.max.x);
}
return;
My mistake was simple adding RaycastHit2D[] result to a List and then applying for OrderBy method, which didn't work either.
However, I'm still wondering why Sort(CompareTo) doesn't work. I presume It is somehow connected to RaycastHit2D[] array type.
Ok now. That was a stupid mistake. After sorting I wrote to the Console "hit in hits" ins$$anonymous$$d of "hit in hitList". Sorting method works perfectly well unlike me. Well, live and learn, right? =)
Your answer
Follow this Question
Related Questions
How can I sort a list of GameObject by name? 1 Answer
Sort list by distance AND by being active 3 Answers
How to sort List of Lists by a certain Value (C#) 1 Answer
UNITY - How to sort items in list with animation step by step (to up/down) 0 Answers
Trying to sort a list of variables. Position in car racing game. 1 Answer