- Home /
 
Enemy Follow Player
I have made enemies and created script that makes them go to a way point(the Players starting point) but i would like the enemies to follow the Player if someone could help me that'd be great. Below is what i have using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI;
public class NPCMove : MonoBehaviour {
 [SerializeField]
 Transform _destination;
 NavMeshAgent _navMeshAgent;
 // Use this for initialization
 void Start()
 {
     _navMeshAgent = this.GetComponent<NavMeshAgent>();
     if (_navMeshAgent == null)
     {
         Debug.LogError("The nav mesh agent component is not attached to " + gameObject.name);
     }
     else
     {
         SetDestination();
     }
 }
 private void SetDestination()
 {
     if(_destination != null)
     {
         Vector3 targetVector = _destination.transform.position;
         _navMeshAgent.SetDestination(targetVector);
     }
 }
 
               }
Answer by lufvilla · May 15, 2018 at 04:52 PM
Hi, you should call SetDestination() inside Update function.
 private void Update()
 {
      SetDestination();
 }
 
              They still move to the starting point of my Player, do i have to remove anything from the code or just leave everything as is and add private void Update() { SetDestination(); } because if that's the case then it doesn't affect the enemies
You should set "_destination" with your player transform in inspector.
Ok so i have three starting enemies and they follow my character but when i make a prefab and put the prefab in my "spawner" the enemies stay in one area and don't move except fot the original three, when i check the prefab the destination wont allow me to put my Player transform in. any idea how to fix this?
Your answer
 
             Follow this Question
Related Questions
How to assign a transform object to Prefab ? 3 Answers
Problems with simple AI script 3 Answers