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

Resolved NullReferenceException on if statement comparing two set variables.

Discussion in 'Scripting' started by cheapcpps, Jul 4, 2022.

  1. cheapcpps

    cheapcpps

    Joined:
    Jul 15, 2020
    Posts:
    53
    In my update event, I have a few if statements, I'm basically going to another class, to check if step is equal to MissionHandlers CurrentStep.
    Code (CSharp):
    1.  public MissionHandler missionHandler;
    2.     public GameObject area;
    3.  
    4.     public int step = 1;
    5.     public string task = "Task";
    6.  
    7.     public bool colliding = false;
    8.  
    9.     void Update()
    10.     {
    11.         if (missionHandler.CurrentStep == step)
    12.         {
    13.             missionHandler.task = task;
    14.             if (colliding)
    15.             {
    16.                 missionHandler.CurrentStep += 1;
    17.             }
    18.         }
    19.     }
    BUT, for some unknown reason on line 17 (which is, if (missionHandler.CurrentStep == step)), I get a NullReferenceException, I printed both variables on the if statement, they're both true, everything in my class is set in the editor, same with every single variable in mission handler, it doesn't make sense, there is literally 0 variables in both classes that are null, area and missionHandler were set via the editor, so I have no clue why this is happening, especially since both of the variables used in the if statement are not null, proven by them both returning 1 in a print statement.
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,144
    Something is null. In this case, if line 11 in your posted script is null, that means missionHandler is null.
    So, your best bet, make sure you don't have an extra copy of the script in your scene accidentally. Remember, the steps are always the same.

    1. Find out what is null.
    2. Find out why it's null.
    3. Fix it.
     
  3. cheapcpps

    cheapcpps

    Joined:
    Jul 15, 2020
    Posts:
    53
    It’s not null, it’s being set to a set variable referencing it, a variable in the missionHandler script returned 1, it can’t be null
     
  4. cheapcpps

    cheapcpps

    Joined:
    Jul 15, 2020
    Posts:
    53
    Nevermind, it was some weird editor bug. It appeared to sometimes return null and sometimes not, restarting the editor fixed my issue.