- Home /
Pick the oldest object from an array.
I'm making a tower defense game and i need my towers to always prioritise enemies that are the closest to the end point. Each enemy has a "age" variable. I'm trying to create an array of enemies that are currently in tower's range. How do i make the tower pick the object with the biggest "age" variable?
Answer by KevLoughrey · May 19, 2014 at 12:23 PM
Something like this should work:
int oldestIndex;
for (int i = 0; i < array.Count() - 1; i++) {
if (array[i].age > array[oldestIndex].age) {
oldestIndex = i;
}
}
//Now attack the object at array[oldestIndex];
Can you explain whats happening in this code? Im trying to rewrite it in javascript into my turret code but i can't quite understand it.
for(...huh??) --> http://www.youtube.com/watch?v=Z4fd2J7imgA
Comparing stuff --> http://www.youtube.com/watch?v=iV3wry4F1J0
Those might help you understand what @$$anonymous$$evLoughrey is showing you.
I'll try to explain as best I can, but this type of thing is usually easier to explain in code :D
You have an array of enemies, and each individual enemy can be accessed by its array index (its position in the array). For example, the first enemy is at array[0], the second at array[1], and so on. If you want to retrieve the age variable of the first enemy, you call array[0].age
So to find the enemy with the oldest age, we have to iterate through the whole array of enemies with a for loop, and check their ages off each other. This is why we use the variable oldestIndex. It stores the index position of the enemy with the largest age value.
The if statement checks to see if the age value of the currently iterated enemy is greater than that of the currently know oldest enemy, and if it is, that enemy becomes the oldest.
@$$anonymous$$evLoughrey http://answers.unity3d.com/questions/710787/how-to-add-colliders-to-an-array-and-pick-the-olde.html this is the exact problem im dealing with, im getting the "Array index is out of range" error. Also should i use list ins$$anonymous$$d of array? I've been reading a lot and everyone says its better in every respect. Thanks for your help.
Answer by Graham-Dunnett · May 19, 2014 at 12:24 PM
Sort the array old-to-new every few frames, then choose the object at the front of the array.