Null reference exeption

Hi! I get an error when i try to check “currentState”


But when i use “currentState?.” its working! But its still null…

Yes. The ? pattern does the null check for you.

So, instead of writing

if (currentState != null) currentState.Exit();

we can just write

currentState?.Exit();

If the currentState is null, C# will not call .Exit() on it. If you leave out the ?, C# will call .Exit() and fail with a NullReferenceException if currentState is null.


Edit
I misunderstood your post. You have a problem in your logic here
image

You check currentState if it’s null. Presume it is not, so we enter the if. We call Exit(), all is still good. Now we replace the reference in currentState with newState. Presume newState is null. Now we have replaced currentState with null, and call currentState.Enter(). We get a NullReferenceException and don’t know why…

You should check currentState again after you changed its reference

if (currentState != null)
{
    currentState.Exit();
}
else
{
    Debug.LogError("Try use null State!");
}

currentState = newState;

if (currentState != null)
{
    currentState.Enter();
}
else
{
    Debug.LogError("Try use null State!");
}
1 Like

@bixarrio’s code can be simplified, and still throw a debug when newState is null:

public void SwitchState(State newState)
{
   currentState?.Exit(); //will only call if not null
   currentState = newState;
   currentState?.Enter();
   if(currentState==null) Debug.Log($"{name} has entered a null state.");
}

the ? qualifier is a C# syntactic sugar that allows us to execute a function on an object only if the object is not null. This works on classes that are not descended from MonoBehavior or ScriptableObjects.

Yes. I was showing it without the ? because the OP said it works with ? but it doesn’t work without it

1 Like

Privacy & Terms