Question by
Plebber · Oct 14, 2016 at 12:48 PM ·
c#navigation
Gameobject follow player on trigger collision
Hi, I am trying to make a gameobject follow the player once the player enters a sphere collider on the gameobject, however instead of following the player when it collides with the trigger, it follows the player from the second I start the test run.
I am at a loss. Any tips would be appreciated.
using UnityEngine;
using System.Collections;
public class DetectPlayer : MonoBehaviour {
NavMeshAgent agent;
public Transform target;
public GameObject Player;
public bool follow = false;
// Use this for initialization
void Start () {
agent = GetComponent<NavMeshAgent> ();
}
// Update is called once per frame
void Update () {
if (follow == true) {
agent.SetDestination (target.position);
}
}
void OnTriggerEnter (Collider col) {
//checking if player collides with trigger
if (col.GetComponent<Collider>().tag == Player.tag) {
follow = true;
}
}
}
Comment
Answer by aallen170 · Mar 03, 2018 at 05:01 PM
Put the following script on the object that will follow the player:
public GameObject target;
NavMeshAgent agent;
void Start () {
agent = GetComponent<NavMeshAgent> ();
}
void Update () {
agent.destination = target.transform.position;
}
void OnTriggerEnter (Collider collision) {
if (collision.tag == "Player")
target = GameObject.FindGameObjectWithTag ("Player");
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612094618im_/https://answers.unity.com/themes/thub/images/avi.jpg)