>I wish to make a specific game object attack a specific target, and after that target is gone (Destroyed), go to the next closest target. As long as all the targets exists, my script works well enough, but once a target is destroyed.. the errors come flying in.>
----------
> I have a public array of 3 targets (3 exactly, won't change), I calculate which one is closest to the gameobject, and it goes there (the "walking" works perfectly). I believe the issue is that even though the target has been destroyed, the array doesn't update itself (it's an update of transforms) so the function will always return the same transform.
----------
> Do you have an idea of how to solve this issue?
using System;
using UnityEngine;
public class attack_target : MonoBehaviour {
public Transform[] hearts;
public float speed = 1f;
private Transform target;
// Use this for initialization
void Start ()
{
target = GetClosestEnemy(hearts);
}
private Transform GetClosestEnemy(Transform[] hearts)
{
Transform bestTarget = null;
float closestDistanceSqr = Mathf.Infinity;
Vector3 currentPosition = this.transform.position;
foreach (Transform potentialTarget in hearts)
{
Vector3 directionToTarget = potentialTarget.position - currentPosition;
float dSqrToTarget = directionToTarget.sqrMagnitude;
if (dSqrToTarget < closestDistanceSqr)
{
closestDistanceSqr = dSqrToTarget;
bestTarget = potentialTarget;
}
}
return bestTarget;
}
// Update is called once per frame
void Update ()
{
while(target != null)
{
float step = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, target.position, step);
}
this.target = GetClosestEnemy(hearts);
}
}
↧