C# trying to find closest target with same tag

OK so, although I am a noob, i managed to get this far without learning how to find the closest tagged target lol.

Basically, what I am doing here is I attach this script to a vehicle, and if the vehicle is within a certain range of the target, then it sends a message to my enemy script which destroys that game object and enables a ragdoll to take its place. Yes, I am running people over :smile: .

It works good with a single enemy (still a little buggy but that will be ironed out soon), but when I add multiple enemies (the goal is a near infinite amount of enemies), it does not target the “closest” enemy, and although I have Gooooogled my butt off, I cannot find a solution that makes sense to me (lack of sleep could be playing a factor.)

Here is my code so far:

using UnityEngine;
using System.Collections;

public class HitByCar : MonoBehaviour {

    public float damage = 100; //amount of damage to inflict
    public float distance; //distance to target
    public float maxDistance = 5.0f; //when target is in damage range
    public GameObject Target; //current target
   
    void Update () {
        //find target with tag
        Target = GameObject.FindGameObjectWithTag("Enemy");
        
        //find distance to target
        distance = Vector3.Distance(transform.position, Target.transform.position);
        
        //if within damaging range
        if(distance < maxDistance ){
        
        //send message to targets script
        Target.SendMessage("ApplyDamage", damage);   

        }

    }

}

Thank you for any help in advance, I wouldn’t have made it this far without these forums. :slight_smile:
-Chris

Unity has a example in the docs doing exactly what you want: Unity - Scripting API: GameObject.FindGameObjectsWithTag

GameObject FindClosestEnemy() {
        GameObject[] gos;
        gos = GameObject.FindGameObjectsWithTag("Enemy");
        GameObject closest;
        float distance = Mathf.Infinity;
        Vector3 position = transform.position;
        foreach (GameObject go in gos) {
            Vector3 diff = go.transform.position - position;
            float curDistance = diff.sqrMagnitude;
            if (curDistance < distance) {
                closest = go;
                distance = curDistance;
            }
        }
        return closest;
    }
1 Like

So in your code you’d set Target to FindClosestEnemy ();

Thank you, its funny cause i looked at that a few times and it didn’t make sense how i would implement it, BUT now it makes perfect sense :stuck_out_tongue:

I still don’t quite understand this. I know it’s a year old but I’m completely stumped on which line of code goes where…

just copy/pasting what i already told someelse who was looking for a solution of finding the largest number in an array.

this can be very comfortably achieved with Linq as you can put all this stuff in one single line, which still looks (more or less) readable

//add the namespace
using System.Linq;

GameObject GetNearestTarget()
{
//so lets say you want the closest target from a array (in this case all Gameobjects with Tag "enemy") and let's assume this script right now is on the player (or the object with which the distance has to be calculated)
return GameObject.FindGameObjectsWithTag("enemy").Aggregate((o1, o2) => Vector3.Distance(o1.transform.position, this.transform.position) > Vector3.Distance(o2.transform.position, this.transform.position) ? o2 : o1);
}

this does the whole job, it iterates through your array, picks the 2 objects o1 and o2 and returns the smaller one (in this case)

so just to break it down a bit
“?” is called ternary operator which can be used instead of “if”

so if you want to know which number is larger you could write

int a = 2;
int b = 3;
int higherNumber;

//now you could write
if (a > b)
higherNumber = a;
else
higherNumber = b;


//or
higherNumber = a > b ? a : b;

and Aggregate does it the same way. Take two elements, compare them to a spcified criteria, which is a comparison of Vector3.Distance in this case, and return the smaller one

1 Like

Thanks for the reply, however, I have multiple enemies (about 20 in-game)

I’m just trying to get a better understanding of where this code should be placed in my script.

how would you go about setting the target to that

Target = FindClosestEnemy();