- Home /
sort children components using siblingIndex inside a for loop
I have created a method to sort cards by Rank (ACE... KING). The method depicts insertion sort algorithm and seems to work fine. I have a button somewhere in the screen and upon clicking this button, this method would be called so that the cards on hand would be sorted by Rank.
Current behavior : only one card is sorted at one time relative to other cards a/c to rank.
Expected behavior : all cards should be sorted at once when I click the button but this is not happening.
I am kind of new with Unity. So, Can anyone help me achieve the behavior I am looking for. Thanks in advance !
public IEnumerator SortByRank(Transform[] cardGameObjects) {
int i, j, min_j;
for (i = 1; i < cardGameObjects.Length; i++) {
min_j = i;
for (j = i + 1; j < cardGameObjects.Length; j++) {
if (cardGameObjects[j].GetComponent<Card>().rank <
cardGameObjects[min_j].GetComponent<Card>().rank) {
min_j = j;
}
}
cardGameObjects[i].SetSiblingIndex(cardGameObjects[min_j].GetSiblingIndex());
yield return null;
}
}
Answer by Hellium · Oct 31, 2020 at 03:30 PM
Code NOT TESTED
public IEnumerator SortByRank(Transform[] cardGameObjects)
{
Card[] cards = System.Array.ConvertAll(cardGameObjects, go => go.GetComponent<Card>());
System.Array.Sort(cards, (card1, card2) => card2.rank - card1.rank);
for(int i = 0 ; i < cards.Length ; ++i)
{
cards[i].transform.SetSiblingIndex(i);
yield return null;
}
}
Hi @Hellium ,
Thank you for your reply but this is quite not working. card2 has null value and unity is throwing exception as follows :
NullReferenceException: Object reference not set to an instance of an object
Game$$anonymous$$anager+<>c.<SortByRank>b__24_1 (Card card1, Card card2) (at Assets/Scripts/Game$$anonymous$$anager.cs:244)
System.Collections.Generic.ArraySortHelper`1[T].InsertionSort (T[] keys, System.Int32 lo, System.Int32 hi, System.Comparison`1[T] comparer) (at <9577ac7a62ef43179789031239ba8798>:0)
I am trying to tweak it at my end but if you have some time, can you please also test at your end ? Thanks.
If you get a NullReferenceException, it means you provide gameObjects without Card
components attached....
I am not sure it's expected, is it?
If not, double check which gameObject you provide to the SortByRank
function. I can't help on this point.
If it's intended:
System.Array.Sort(cards, (card1, card2) =>
{
if(card1 == null) return 1;
if(card2 == null) return -1;
return card2.rank - card1.rank;
});
Yeah, I had one object with no Card attached and that was causing the issue. Now, it has been resolved and your code worked like a charm. Thanks !
Your answer
Follow this Question
Related Questions
Having only one of the same gameobjects in a scene. Photon Pun 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Instantiated object not showing in scene or hierarchy 2 Answers
,How to stop jump animtion 1 Answer