Help with distance between multiple objects

Hey guys so I am trying to figure out how to calculate the distances between x enemies and a cannon, so the cannon knows which enemy is closest to him. I tried doing something like:

for (int i = 0; i < maxNumberOfenemies; i++)
{

   float enemyPositions _= GameObjects enemies*.transform.position;*_

float fdistance = Vector3.Distance(enemyPositions*, transform.position);*
I tried to then figure out the distance but still cant, i am having problems
}
thanks in advance :slight_smile:

Use a minDistance variable set to a large value, and an enemy variable set to -1. Then, inside your loop, check to see if the fdistance is less than your minDistance. If it is, make a note of the value of i in your enemy variable. On exitting the loop, minDistance is the closest enemy, and enemy in the closest one.

Note that Vector3.Distance is an expensive operation if you have a lot of enemies. Instead, subtract transform.position from enemies*.transform.position. This is the vector from the camera to the current enemy. Then use sqrMagnitude. The docs for the sqrMagnitude API have an example that you might care to look at.*

The easier, faster and safer solution is to let Unity keep the enemy list for you. Create an empty object, name it “Enemies” and attach to it the enemy creator script. Every time a new enemy is created, make it a child of “Enemies”.

In the cannon script, find “Enemies” at Start, and in Update, check the distance of all “Enemies” children to find the closest one, then rotate to it and shoot.

This is your enemy creator script (attached to the object named “Enemies”) - the only modification is the “childing” of the new enemy to the creator:

private float fTimer = 0;
private float fSpawnTime = 20;

private const int iEnemySpawnLocTotal = 7;
private GameObject[] goEverySpawnLocation = new GameObject[iEnemySpawnLocTotal];
public GameObject enemy1;

void Start() {
  goEverySpawnLocation = GameObject.FindGameObjectsWithTag("enemySpawn");
}

void Update() { 
	fTimer += Time.deltaTime;
	if(fTimer > fSpawnTime) {
		int randomNumber = Random.Range(0, iEnemySpawnLocTotal);
		fTimer = 0;
		GameObject myPrefab = (GameObject)Instantiate(enemy1);
		myPrefab.transform.position = goEverySpawnLocation[randomNumber].transform.position;
		// make the new enemy a child of this object ("Enemies")
		myPrefab.transform.parent = transform; 
	} 
}

And this is the cannon script (assigned to each cannon):

private GameObject enemies; // reference to the Enemies object

void Start(){
	enemies = GameObject.Find("Enemies");
}

void Update(){

	float minDistance = Mathf.Infinity; // initiate distance at max value possible
	Transform target = null; // use this to detect the no enemy case
	foreach (Transform enemy in enemies.transform){
		float enemyDistance = Vector3.Distance(enemy.position, transform.position);
		if (enemyDistance < minDistance){ // if it's closer than the others...
			minDistance = enemyDistance;    // record its distance...
			target = enemy;                 // and its transform
		}
	}
	// target will still be null if no enemy exists
	if (target){ // but if the closest enemy found...
		// rotate towards the target transform and shoot
		transform.LookAt(target);
		// draw a line to the enemy found
		Debug.DrawLine(transform.position, target.position,  Color.green);
	}
}

I really appreciate your help, and thank you for all the help. I don’t really understand why it is not working, however I have decided to go another route anyways. I have to get back to the drawing board and figure out my mechanics first because I keep changing my mind every few days. So anyways, thanks again.