using UnityEngine.AI;
using UnityEngine;
public class Enemy : MonoBehaviour
{
NavMeshAgent agent;
public GameObject player;
private void Start()
{
agent = gameObject.GetComponent<NavMeshAgent>();
}
private void Update()
{
agent.SetDestination(player.transform.position);
}
This is the code. As you can see, I’ve used agent.SetDestination(player.transform.position).
The problem is that the the enemy is a prefab so I can only use prefabs as references. So the player prefab is used to reference the player GameObject. But due to this, the enemies all path to 0,0,0 the original position of the player prefab and not the current player transform. How to rectify this? I know it’s probably something really simple but it’s driving me crazy I can’t figure it out. Thanks!
Just to make that clear: You can not save such a reference to an instantiated object into a prefab. You have to assign this reference at runtime when you dynamically instantiate your enemy. There are generally a couple ways to do this:
Each enemy could search for the player object in the scene and assign their target themselfs once they have found the player. This works, but adds quite a bit of overhead per enemy instantiation.
Some games may use Physics.OverlapSphere and trigger colliders to detect potential close targets. This of course depends on the type of game. If an enemy should always know where the player is, this approach would be wasteful and may not have the desired effect.
The usually best approach: Have the code that instantiate the enemy have a reference to the player which if can set after the enemy has been instantiated. This is usually the best approach when the target is known ahead of time and there’s only one target.