Z
Z
Zefirot2021-11-29 21:44:49
Unity
Zefirot, 2021-11-29 21:44:49

How to sort objects by their variables?

I have an object and it has a variable

public int CountTest = 1;
// объекты хранятся в массиве
public PrefabTest[] ArrayPrefabTest;
// то есть доступ до переменной
ArrayPrefabTest[0].CountTest = 1;
ArrayPrefabTest[1].CountTest = 15;
ArrayPrefabTest[2].CountTest = 3;
ArrayPrefabTest[3].CountTest = 30;

over time, these variables take on different values ​​and when iterating over the array
for(int i = 0; i < ArrayPrefabTest.Length; ++i){
  if(ArrayPrefabTest[i].CountTest == ....

I need to do different things there, but that's what I need - I need them to be sorted out of order, but re-sorted by this variable (for example, in descending order), that is, so that I get the array in the following order
ArrayPrefabTest[3].CountTest = 30;
ArrayPrefabTest[1].CountTest = 15;
ArrayPrefabTest[2].CountTest = 3;
ArrayPrefabTest[0].CountTest = 1;

How to sort it like that, even if it is a separate temporary array, or a set of keys in the right order, such as 3,1,2,0...
Tell me how?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
freeExec, 2021-11-29
@Zefirot

foreach (var pref in ArrayPrefabTest.OrderByDescending(x => x.CountTest)) { }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question