I need this script to when the zombie spawns in to find the closest object with the name player within 10 meters, and set that object as the target. Right now it is not picking anything up with the tag Player even though the player is spawned in.
using UnityEngine;
using System.Collections;
public class zombieai : MonoBehaviour {
public GameObject Target;
public float speed;
public Transform targettrns;
void Start(){
FindClosestEnemy ();
speed = 1f;
}
GameObject FindClosestEnemy() {
GameObject[] Targets;
Targets = GameObject.FindGameObjectsWithTag("Player");
GameObject closest = null;
float distance = Mathf.Infinity;
Vector3 position = transform.position;
foreach (GameObject go in Targets) {
Vector3 diff = go.transform.position - position;
float curDistance = diff.sqrMagnitude;
if (curDistance < distance) {
closest = go;
distance = curDistance;
}
}
GameObject Target = closest;
return closest;
}
void FixedUpdate (){
if (Target != null) {
targettrns = Target.transform;
float step = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, Target.transform.position, step);
transform.LookAt (targettrns);
}
}
}
↧