- Home /
Order a GameObject array based on an int property of each object?
public void turnOrder () {
GameObject[] playerCharacters;
playerCharacters = GameObject.FindGameObjectsWithTag ("ActiveCharacter");
playerCharacters = playerCharacters.OrderByDescending (x => x.curAgi).ToList ();
Above is my code, and here's what I'm trying to achieve:
I'm finding all characters with the tag "ActiveCharacter" and putting them into the array of game objects "playerCharacters". The goal is to then order them based on their individual "curAgi" values, which is an integer and is unique to each of the characters.
I have used the following:
z = (playerCharacters.Length);
Debug.Log("ArrayLength:" + z);
To confirm that the array has in fact been populated.
The issue appears (I say appears, but it's rather blatantly obvious considering the error message I am getting and the red highlight) to be with curAgi. Despite being aware of this, I'm at a loss as to the solution. I have looked at previous questions and attempted to follow the advice therein for the past few hours, yet am still coming up blank.
Any and all assistance is very much appreciated.
Answer by cjdev · Aug 16, 2015 at 08:06 AM
It seems that you're trying to access a property (curAgi) that is actually in a script component of the GameObject rather than the object itself. You'd first have to use GetComponent() to get the script with the value that you're looking for in order to sort them.
Absolutely correct, however I'm still having trouble setting everything up correctly so that the list is ordered.
public void turnOrder () {
List<GameObject> turnList= new List<GameObject>();
GameObject[] playerCharacters;
playerCharacters = GameObject.FindGameObjectsWithTag("ActiveCharacter");
foreach (GameObject Character in playerCharacters) {
CharacterScript charTracker = Character.GetComponent<CharacterScript> ();
turnList = playerCharacters.OrderByDescending(x => charTracker.curAgi).ToList ();
}
I can return the contents of the List, but they are not being ordered. Any ideas? I must admit that I have absolutely no idea how to proceed from here.
$$anonymous$$aybe this will help you as well, I asked it long ago :)
I believe the solution is there in Cherno's answer. In your case it would be (although this is untested):
turnList = playerCharacters.OrderByDescending(x => x.GetComponent<CharacterScript>().curAgi).ToList ();
In your example above the problem is that you're trying to order the GameObject list items by the unrelated CharacterScript list.
That is absolutely fantastic. I was just going over the question which Cherno linked when I saw this response, and the code you provided works perfectly.
$$anonymous$$uch appreciate the assistance!