- Home /
Creating an ordered list from a variable
I am trying to create and ordered list based off a speed variable that is stored on other objects. So if the objects have a speed of 3, 7, 1, and 5 respectively, the code would order the objects from greatest to smallest based off the speed variable (7, 5, 3, 1). The best way I can think to do it is use getcomponent to get the speed variable, and then create the list based off the info pulled. From the basic research i've done on list collections (http://unity3d.com/learn/tutorials/modules/intermediate/scripting/lists-and-dictionaries) I feel like they might do the job, but I'm not positive. Is there a better way to do what I'm trying to do, or is the way I described the way to go, and if it is the way to go how would I go about creating the list?
Answer by vexe · Aug 09, 2014 at 03:09 AM
Use LINQ
public class MyObject : MonoBehaviour
{
public int speed;
}
var orderedList = Object.FindObjectsOfType<MyObject>()
.OrderBy(o => o.speed)
.ToArray(); // Or ToList, depending on what you want
This orders them in an ascending order. If you want descending order use OrderByDescending instead.
Note: Add using system.Linq;
at the top.