Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Player GameObject showing as null, and sometimes not.

Discussion in 'Scripting' started by IncrediblyWalrus, Apr 19, 2022.

  1. IncrediblyWalrus

    IncrediblyWalrus

    Joined:
    Jul 22, 2019
    Posts:
    46
    Hi,

    I'm trying to use the NavMesh component, specifically the SetDestination part.

    It runs fine in Start() (as a test), however, when I try using it so it's constantly following the player, for example in the Update method, it just doesn't work, it instead throws a bunch of Null errors for the gameObject (the player).

    This is basically the simple code that I'm using:


    Code (CSharp):
    1. void Start()
    2. {
    3.     target = GameObject.FindWithTag("Player");
    4.     NavMeshAgent agent = GetComponent<NavMeshAgent>();
    5.  
    6. }
    7.  
    8. void Update()
    9. {
    10.  
    11. agent.SetDestination(target.transform.position);
    12.  
    13. }
    Obviously missing some things out but that is basically what it is trying to do. I should mention, maybe, that I am using PUN 2 with the Player being a prefab, unsure if this as has to do with it. If you're wanting more code just let me know.

    Edit: I'm an idiot, solved.
     
    Last edited: Apr 19, 2022
  2. SourGummi

    SourGummi

    Joined:
    Nov 14, 2021
    Posts:
    96
    null means it doesnt exist, or isnt set to a correct object name.

    if you want something to always follow a specific object in the scene, just add it to the object in the scene.
    Code (CSharp):
    1. transform.position
    will then always be the position of the host object.