Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Have a look at our Games Focus blog post series which will show what Unity is doing for all game developers – now, next year, and in the future.
    Dismiss Notice

Question Sorry if this is really dumb but..

Discussion in 'Scripting' started by KeyboardStudios, Sep 25, 2022.

  1. KeyboardStudios


    Jul 11, 2020
    Code (CSharp):
    1. using UnityEngine.AI;
    2. using UnityEngine;
    4. public class Enemy : MonoBehaviour
    5. {
    6.     NavMeshAgent agent;
    7.     public GameObject player;
    9.     private void Start()
    10.     {
    11.         agent = gameObject.GetComponent<NavMeshAgent>();
    12.     }
    14.     private void Update()
    15.     {
    16.         agent.SetDestination(player.transform.position);
    17.     }
    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!
  2. DevDunk


    Feb 13, 2020
    A prefab is an asset. If you spawn a player the prefab does not change, the instantiated object does. So reference the spawned player to track it
    KeyboardStudios and Bunny83 like this.
  3. Bunny83


    Oct 18, 2010
    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.
    KeyboardStudios and DevDunk like this.