find the closest target

Currently my script will target the first ‘Target’ in it’s range (furthest) but will not target the closest target which is what I’m trying to get done. Any help would be appreciated.

//loop the following section every 0.1second indefinitely
while(true){
	//check there's no target or the target is already out of range
	if((target==null || !target.gameObject.active) || Vector3.Distance(target.position, thisT.position)>range){
		//check for all unit within range
		var allTargets=Physics.OverlapSphere(thisT.position, range, layerMask);
		//if there are target within range
		
		if(allTargets.length!=0) {
			//just assign the first target
			target=allTargets[Random.Range(0, allTargets.length)].transform;
			targetCom=target.gameObject.GetComponent.<Creep>();
		}
		
		
		//else dont set any target
		else target=null;
	}
	yield WaitForSeconds(0.1);

(Warning: this might not be the most efficient, but it will work)

create a temporary list of all tings in range, and then cycle through them, and then

if(Vector3.Distance(target.position, thisT.position)> Vector3.Distance(thing2.position, thisT.position)){
    target = thing2;
    // remove thing2
}else{
    // remove thing2
}

and do this in a loop for all things in your list.

Pretty much everything you need is explained in these 3 videos, glad i can help :slight_smile:

  1. 8. Unity3d Tutorial - Targetting Enemies 1/3 - YouTube
  2. 9. Unity3d Tutorial - Targeting Enemies 2/3 - YouTube
  3. 10. Unity3d Tutorial - Targeting Enemy 3/3 - YouTube

The function should actually just give you a target, regardless of its distance (since Random.Range just returns a random number between min and max, the range has nothing to do with the distance).

To get the closest target, either sort your target array and get the first entry or just iterate over the list and check which target is the closest. Try something like

if(allTargets.length!=0) {
var minSqrDistance = range*range; // if sqrmagnitude > range^2 it would be out of reach
var currentTargetIndex = 0;

for(var i = 0; i < allTargets.length; i++)
{
    var sqrMag = (thisT.position - object.transform.position).sqrMagnitude;
    if(sqrMag < minSqrDistance)
    {
        minSqrDistance = sqrMag;
        currentTargetIndex = i;
    }
}
target=allTargets[currentTargetIndex].transform;
targetCom=target.gameObject.GetComponent.<Creep>();
}

Note: not sure if this will work - I’m not a JavaScript guy - but it should give you an idea.

Ok, update on what I’ve done. I found that using JS was a bit too much for me to try to wrap my head around so I decided to rebuild my script (which wasn’t mine to begin with). I’m currently working with C# and I haven’t had any issues. Thank you very much for the assistance and answers.