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 .
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.
-Chris
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