So, I have this script, which is made to set the nearest enemy with a certain tag.
whenever I try to run the program i get an error message saying it has not been set.
And I’m like;
“Well I know it hasn’t been sit it gets set during the script!”
please help .-.
Here’s the Code:
public Transform target;
NavMeshAgent agent;
void Start (){
agent = GetComponent<NavMeshAgent> ();
}
void Update (){
if (target = null) {
GetClosestEnemy();
}
}
Transform GetClosestEnemy(){
GameObject[] gos;
GameObject closest = null;
gos = GameObject.FindGameObjectsWithTag ("ENEMY1");
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;
}
}
print ("Target Name:" + closest.name);
print ("Total GameObjects Found:" + gos.Length);
agent.SetDestination (closest.transform.position);
return closest.transform;
}
}