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. Dismiss Notice

Question How to get something to go where I point

Discussion in 'Scripting' started by Bannanaking3, May 11, 2023.

  1. Bannanaking3

    Bannanaking3

    Joined:
    Jun 21, 2022
    Posts:
    109
    I have a character that (in theory) goes to an enemy when I point at it. Currently, I'm using a raycast that checks if the thing is an enemy and then saves it as an object in the pointer script on the player

    Code (CSharp):
    1.   RaycastHit hit;
    2.         if(Physics.Raycast(transform.position, transform.forward, out hit, 40))
    3.         {
    4.             WhipEnemy we = hit.transform.GetComponent<WhipEnemy>();
    5.  
    6.             if (we != null)
    7.             {
    8.                 Target = hit.transform.gameObject;
    9.                 attacking = true;
    10.  
    11.             }
    12.         }
    then the character script references that and should pathfind to it

    Code (CSharp):
    1.   agent.SetDestination(ns.Target.transform.position);
    2.         if(ns.Target = null)
    3.         {
    4.             isFollowing = true;
    5.             isChasing = false;
    6.         }
    problem is the character script returns a null reference error when I point. is there a better way of doing this?
     
  2. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,588
    You did not show the full code but presumably Target is not always set. For example, before you give it its first value. Your character controller has a null check for Target, but above that you still use ns.Target.transform.position in your SetDestination call. So if Target is null, then that line will trigger a NullReferenceException. You probably want to move it into your null check. If that does not do what you want it to do you might want to provide more context and/or code.
     
  3. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    3,495
    Classical mistake. In this line you SET ns.Target to null. You did not check it against null. Comparison is done with
    ==
    . A single
    =
    means assignment.

    Apart from that in the line before you already try to access the transform of the Target. When the target is actually null that line would throw a null reference exception. So it should be inside the null checked if body.

    So something like that:
    Code (CSharp):
    1.  
    2.         if(ns.Target != null)
    3.         {
    4.             agent.SetDestination(ns.Target.transform.position);
    5.         }
     
    Yoreki likes this.
  4. Bannanaking3

    Bannanaking3

    Joined:
    Jun 21, 2022
    Posts:
    109

    OH my GOOOOOD every time. thanks bunny. I swear that mistake is gonna be the death of me.