NullReferenceException for the level up event

Could not figure this one out but I get a NullReferenceException when I call the onLevelup event when I UpdateLevel().
Capture

If I comment out line 33 I get no errors. all this does is restore the players health and if I comment out the RestoreState() method onLevelup() still gives me a null reference exception. On further tests I found that when the next attack hits after the killing blow the code resolves and the health and level updates.

Welcome to the community @jmesa

If there are no listeners to an event, it is null. When invoking events you should always check if they are null first

There are 2 ways to do this: The old way

if (onLevelUp != null)
{
    onLevelUp();
}

and the new way

onLevelUp?.Invoke();

Both work exactly the same. The new way is just ‘shorthand’ for the old way

Thanks bixarrio!
Not sure why a null check would fix this (which it did)? If it was null then I can understand why this error was thrown but it is not because the code executed fine when I checked for null. Was the error caused by me not checking?

No, it will raise a NullReferenceException if there are no listeners. The error is caused by nothing subscribing to onLevelUp

Strange I thought that this was adding the subscriber to the Health class when I put this in the Start()
Capture
The only thing I added to the code was the check and now it works?

If something calls BaseStats.GetStat() before any methods that subscribe to the event run their Start() (say if Health subscribes to onLevelUp, but another component gets a Stat in their Start() which happens to run before Health()) then the event will be empty. Even when you’re positive that the event will have subscribed listeners, you should null check.

1 Like

Sorry, only saw this this morning. @Brian_Trotter has it pretty much summed up.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms