- Home /
Not finding closest Object with tag player.
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);
}
}
}
Answer by Creeper_Math · Jan 03, 2017 at 08:33 PM
You only called the FindClosestEnemy();
script, not put it into a varaible (it's not just a void there)
You need to direct it to the target gameobject
void Start(){
Target = FindClosestEnemy ();
speed = 1f;
}
Thanks you so much! ,but i still need to it only search within 10 meters.
Something that @SPOTNINJADUD7890 has works, specifically what follows
GameObject FindClosestEnemy() {
GameObject[] Targets = GameObject.FindGameObjectsWithTag("Player");
// Above is because you can't state a local variable without setting it an initial value in the same call, weird, but it at least happens to me
GameObject closest = null;
foreach (GameObject PossibleTarget in Targets) {
if (Vector3.Distance(transform.position, PossibleTarget.transform.position) <= 10) {
if (closest == null || Vector3.Distance(transform.position, PossibleTarget.transform.position_ <= Vector3.Distance(transform.position, closest.transform.position)) {
closest = PossibleTarget;
}
}
}
return(closest)
}
Also, are u on a 1 unit to 1 meter scale? (I don't know if that's a problem or not, Don't know unity's measurements much)
Answer by SPOTNINJADUD7890 · Jan 03, 2017 at 08:56 PM
I have found how to only follow the player within 10 meters by myself.
if (Vector3.Distance (Target.transform.position, this.transform.position) <= 10) {
targettrns = Target.transform;
float step = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards (transform.position, Target.transform.position, step);
transform.LookAt (targettrns.FindChild ("humanmalemodeltxt"));
}