AI NavMeshAgent doesn’t follow player, can anyone help me out?

Hello, I made a NavMeshAgent Ai that follows a player around the scene, but ever since I started using the Unity Netcode for GameObjects, the AI wont follow the player around because the NetworkManager uses a playerPrefab and once the prefab is spawned in, the manager creates a clone of the player. The AI is set to follow the original player prefab not the clone made by the NetworkManager.
Here is my code:

public Transform enemyTarget;

protected NavMeshAgent myAgent;

void Start()
}
myAgent =GetComponent();
{

void Update()
}
myAgent.SetDestination(enemyTarget.position);
{
Can anyone help me out with creating a code that will allow the AI to follow the player Prefab clone that the NetworkManager spawns in the scene?
Thanks

Hi,

I’m not sure if you already solved this but, it isn’t clear how your game was originally getting the player object. As you have a public Transform it suggests that either you were dragging the player object into the field in the inspector or setting it with some other code.

You could add an entry in the Start function of your code above to find a reference to the player object at runtime and pass its transform to the enemyTarget transform…

enemyTarget = FindObjectOfType<NameOfScriptOnThePlayer>().transform;

(Replace the text NameOfScriptOnThePlayer with that of an actual script component you have on the player that is unique to the player)

2 Likes

Note: For the above to work, the player object would need to be spawned into the scene prior to this code trying to find it, otherwise you may get a null reference error.

1 Like

The issue is that using the players transform directly might not actually be on a legal mesh position (for instance, when the model is not placed neatly on the mesh, or a rebake made it be placed outside a walkable area).

I solve this by doing a RayCast downward from a slight offset above the players position, using a mask so it only checks for things on specific layers (the ones all my geometry is on). Then I have my legal position point, which is more accurate then using the transform of something that can, well… potentially jump. Or fall. Or climb. And not be on a mesh momentarily.

Your code itself is fine, you just need to check whether the position you want to go is actually on a mesh, and feed it a more precise point.