How do I make my units stop when the enemy is within a certain distance?
The game has two sides sending enemies from their respective bases (one at left and one at right along z axis)
I can send units at the base on the right but when they get close to enemy units i want them to stop.
(preferably without collision since i dont have anything set up for colliders…)
which unit do you want? the closest? heres somethin im workin on, so not nearly perfected yet, but it gets units tagged as enemy, then for each gets distance, if dist < weaponRange it adds to weaponTargetArray, then it gets the closest and sets as currentTarget.
well my code does a lot of stuff that even im not using atm, basically this is all you need:
function Radar(){
var closestTarg : GameObject;
var maxDetectionRange = 300.0;
var enemies = GameObject.FindGameObjectsWithTag(“Target”); //—this assigns all objects with “tag” to the variable ‘enemies’
for(var e in enemies){ //----------this loops through each obj in enemies and checks distance
var dist = Vector3.Distance(e.transform.position, transform.position);
if(dist < maxDetectionRange){
maxDetectionRange = dist;
closestTarget = e;
}
/-----------as it loops through it sets closest target as object with least distance, and sets that distance to be the one checked for following objects, this way as it goes through list you will end up with the absolute closest object. --------------------/
public void Radar(){
GameObject closestTarg;
float maxDetectionRange = 300.0f;
GameObject[] enemies = GameObject.FindGameObjectsWithTag("Target"); //---this assigns all objects with "tag" to the variable 'enemies'
foreach(GameObject e in enemies){ //----------this loops through each obj in enemies and checks distance
float dist = Vector3.Distance(e.transform.position, transform.position);
if(dist < maxDetectionRange){
maxDetectionRange = dist;
closestTarget = e;
}
/*-----------as it loops through it sets closest target as object with least distance, and sets that distance to be the one checked for following objects, this way as it goes through list you will end up with the absolute closest object. --------------------*/
}
}
Not pretty just copy and pasted his code and threw it in Notepad