Navmesh get enemy to follow player.

Hi all,

I have a scene setup with a player and some spawnpoints dotted around to spawn my enemies.

I also have a navmesh.

The spawn script chooses a spawn point at random and instantiates an enemy prefab at that point.

What I am trying to do is simply get my enemies to follow my player.

Here is my script to make the enemy prefab follow the player.

using UnityEngine;
using System.Collections;

public class EnemyAI : MonoBehaviour {
	public Transform M_Player;
	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update ()
		
	{

		GetComponent<NavMeshAgent>().destination = M_Player.position;
	}


}

If I get rid of the spawn points and add the enemy directly to my scene the script works fine.
If I use spawn points, I can’t drag my player object onto the transform slot of my script.

How do I add my players transform to the script when my enemy is still a prefab in the inspector and not part of the game scene?

You could hold a static reference to the player in your player script so you can access it from your enemies script and find its transform like this:

public static reference;

void Awake(){
	reference = this;
}

Then in your enemy script you can access the player script like this:

    void Update(){
    GetComponent<NavMeshAgent>().destination = Player.reference.transform.position;
}

Or you could tag your player as ‘player’ and then search for an object with that tag:

void Start(){
	player = GameObject.FindGameObjectWithTag("Player");

	if(!player){
		Debug.Log("Make sure your player is tagged!!");
	}
}

void Update(){
	GetComponent<NavMeshAgent>().destination = player.transform.position;
}

private NavMeshAgent agent;

void Awake(){
agent = GetComponent<NavMeshAgent>();
}

void Update(){
agent.SetDestination(player.transform.position);
}