I’m very confused as to how to use this method.
I have this code:
var listTurrets = new List.<GameObject>();
I want to write a simple function that finds the closest gameObject in the list to the gameobject passed in as a parameter.
i know i can do this:
var indexToReturn;
var tempDistance;
for(i=0; i < listTurrets.Count;i++)
{
calculate distance, compare with previous,replace index if smaller distance.
}
This is easy cause i know “i” represents each object in the list as the loop iterates through it.
But for the inbuilt method listTurrets.ForEach() i dont see how to access the object in the list as the method iterates through them.
I’ve been searching and searching and cant find a straight explanation anywhere…
Any assistance to put this confusion to rest is much appreciated
// Target the first tower in the array of targets available to the tower
currentTarget = towerTargets[0];
// Calculate the distance from the tower to the target
float distanceToLastTarget = Vector3.Distance(this.gameObject.transform.position, currentTarget.transform.position);
// Find the closest enemy of the available targets and set it as the current target of the tower
for (int i = 1; i < towerTargets.Count; i++)
{
if ((Vector3.Distance(this.gameObject.transform.position, towerTargets*.transform.position)) < distanceToLastTarget)*
{*
_ currentTarget = towerTargets*;_
_ }_
_ }*_ It basicly sets the first “enemy” in the target list as the towers current target and then checks if any enemies are closer one by one. If there is an enemy that is closer that enemy replaces the current target. That way you will always come out of the for loop with the target that is closest to the tower.