I have a array of gameObjects, and i want to see witch one has traveled the furthest, so i can attack them first. how do this? I already have a script that is keeping track of distance traveled.
this is ware i am, i feel that i am completely lost in how to do this properly.
void ShootFirst(){
GetTargets();
foreach( GameObject obj in allTargets){
int arrayNumber;
allTargetDistanceMoved[arrayNumber] = allTargets[arrayNumber].GetComponent<Minion>().distenceTraveled;
arrayNumber ++;
}
}
using UnityEngine;
using System.Collections;
public class Tower : MonoBehaviour {
//Tower Settings
public int towerRange;
public int attSpeed;
public int damage;
//player settings
public bool shootFirst;
public bool shootStrongest;
public bool dontShoot;
//Tower tools/objects
public Sprite projectile;
//Tower Variables
public GameObject currentTarget;
public GameObject[] allTargets;
public float[] allTargetDistanceMoved;
// Update is called once per frame
void Update () {
if(dontShoot == true)
return;
if(shootFirst == true){
ShootFirst();
return;
}
if (shootStrongest == true)
ShootStrongest();
}
void ShootFirst(){
GetTargets();
foreach( GameObject obj in allTargets){
int arrayNumber;
allTargetDistanceMoved[arrayNumber] = allTargets[arrayNumber].GetComponent<Minion>().distenceTraveled;
arrayNumber ++;
}
}
void ShootStrongest(){
GetTargets();
}
void GetTargets(){
allTargets = GameObject.FindGameObjectsWithTag("Enemy");
}
}
using System.Linq; //this namespace helps alot with such operations
//lets say this is your script that keeps track of the distances travelled for each Enemy
class DistanceScript : MonoBehaviour { public int distance; }
//this shall be the array in which your contacts with the "distance script" are
public GameObject[] m_GameObjects
//then this method returns the enemy which travelled the most
public GameObject GetNearestTarget()
{
return m_GameObjects.Aggregate((o1, o2) => o1.GetComponent<DistanceScript>().distance > o2.GetComponent<DistanceScript>().distance ? o1 : o2);
}