hi I’m new here in unity and i would like to ask why is my code not working? you see have this game where i instantiate dynamically zombies and when my player hit the collider of the zombie prefab it will move towards the player…
public class detection : MonoBehaviour {
public Transform target;
public float speed;
GameObject targ;
GameObject spawn;
Transform Spawn;
// Use this for initialization
void Start () {
targ=GameObject.FindGameObjectWithTag("Player");
target=targ.transform;
spawn=GameObject.FindGameObjectWithTag("spawn");
Spawn=spawn.transform;
}
// Update is called once per frame
void Update () {
float step= speed*Time.deltaTime;
if(collider.isTrigger)
{
Spawn.transform.position=Vector3.MoveTowards(transform.position,target.position,step);
}
}
}
You’re pretty close but I think you may have misunderstood the isTrigger property.
I think in your scenario you need to find the Collider on your zombie and set isTrigger to true. This informs Unity that you want to know when something collides with the zombie. (If isTrigger is set to false, then Unity will handle collisions with Rigidbodies by applying the physics rules)
Then, you need to add a new method to your zombie/detection class called OnTriggerEnter as follows:
GameObject target;
void OnTriggerEnter(Collider other) {
// did we collide with a player?
if(other.gameObject.tag == "Player") {
// remember which player we're chasing
target = other.gameObject;
}
}
Now, whenever the player gets too close to a zombie, that zombie remembers that player using the new target field.
Finally you can tell your zombie to MoveToward the player as part of the update…
void Update () {
// are we tracking a player?
if(target != null) {
// chase them
float step= speed*Time.deltaTime;
Spawn.position = Vector3.MoveTowards(Spawn.position, target.transform.position, step);
}
}
Code is untested of course, but hopefully this will help you.