hi!
i have a few targetobjects an an enemy in my unity scene. i want that the enemy finds the closest targetobject and goes to it, using nav mesh agent. finding the closest targetobject works, also moves the enemy, but he will always go to the point 0,0,0, no matter where the targetobjects are. does anybody know why? i also wantet to ask, if someone could tell me, how i can complement my script so that the enemy, after he found and went to a targetobject, will move forward to the next closest one and not stay with this, because it is the closest for now. thanks a lot!
so far, i wrote the following script:
private var targetPosition : Vector3;
private var directionNavAgent : NavMeshAgent;
function Start()
{
directionNavAgent = GetComponent(NavMeshAgent);
directionNavAgent.destination = targetPosition;
}
print(FindClosestTarget().name);
function FindClosestTarget () : GameObject {
var gos : GameObject[];
gos = GameObject.FindGameObjectsWithTag("Target");
var closest : GameObject;
var distance = Mathf.Infinity;
var position = transform.position;
for (var go : GameObject in gos) {
var diff = (go.transform.position - position);
var curDistance = diff.sqrMagnitude;
if (curDistance < distance) {
closest = go;
distance = curDistance;
}
}
return closest;
targetPosition = closest.transform.position;
}