- Home /
Sorting gameobjects in an array c
Hello guys.
I had a question and found my answer on unityAnswers about sorting gameobjects in arrays but I still don't understand what is going on. Here's the original post: http://answers.unity3d.com/questions/271910/c-sorting-a-list-of-gameobjects-alphabetically.html
The answer they gave to sort the array of gameobjects what this:
using System.Linq;
// ...
void FindWayPoints()
{
WayPoints = GameObject.FindGameObjectsWithTag("Waypoint").OrderBy( go => go.name ).ToArray();
}
What does the "go => go.name" mean? Thanks! Chris
Answer by Huacanacha · Oct 23, 2013 at 11:26 PM
go => go.name
This is a code block (closure) that is run on each item in the list to determine what to sort the list by. In laymans terms:
"go" - variable to hold each object in your list (all GameObjects in this case, hence 'go')
"=>" - run this code!
"go.name" - the code being run... get;s the name property from each "go" variable.
The result is used to sort the list (which could be List, an array etc), and hence the list is sorted by GameObject name.
Note that there are more efficient ways of sorting arrays in C#, but unless this is used in a performance critical part of your code it shouldn't matter.
Answer by rutter · Oct 23, 2013 at 11:19 PM
go => go.name
It's a lambda expression, which is a shorthand way of expressing an anonymous function. In this case, it takes a GameObject and returns its name.
OrderBy is a LINQ function. When called on a collection (such as the array that's returned by FindGameObjectsWithTag), it evaluates the expression for every GameObject in the list, then sorts based on the results.
As a purely hypothetical example, you could instead sort by each GameObject's position on the z-axis:
go => go.transform.position.z