- Home /
What's the best way to make sure objects go into a list in the proper order?
I have bunch of objects (dozens) that all have a unique ID number. So like, "ExampleObject1" would have an "ObjectID" of 1. What I want to do now is figure out the best way to put all of those objects into a list in order of their ID numbers (they won't necessarily be ordered sequentially in the hierarchy because their position in the hierarchy regularly changes). It seems like the "brute force" way to do it would be like so...
for (int i = 1; i < NumberOfObjects; i++)
{
var objects = FindObjectsOfType<ExampleObjectScript>();
foreach (ExampleObjectScript o in objects)
{
if (o.ObjectID == i)
ObjectsList.Add(o.gameObject);
}
}
...But that seems like a pretty wasteful approach to loop through all the objects each time, just to find the one object to add next. Is there any more streamlined or practical way to do this?
Answer by SirPaddow · Jun 20, 2019 at 03:08 PM
That's not really related to Unity, and if you want to code this algorithm yourself, you should probably study different sorting algorithms to understand which ones are the best.
For my part, I would probably do it with Linq, like this:
ObjectsList = FindObjectsOfType<ExampleObjectScript>().OrderBy(t => t.ObjectID).Select(t => t.gameObject).ToList();
Biggest downside with linq is the generated garbage, so depending on the situation, it may not be the best solution, but if this operation is only done once, it's perfectly fine.
The current plan is to use it for a Save function, so I wouldn't necessarily be only doing it once.
The problem would be if it's an operation you do at every frame (in the Update method for instance). If you save at some points, it's not a problem ;)
Your answer

Follow this Question
Related Questions
How to rearange the order of a list after an item was removed? 0 Answers
Undo/back system using a List/Array 2 Answers
Lists of lists in Boo gives error: "Type 'object' does not support slicing." 0 Answers
Saving a List of variables between scenes 2 Answers
Swapping items between separate lists. Inventory troubles in C# 0 Answers