- Home /
Turned into bug report
Unity accepts default parameter in event subscription but fails
I encountered a really strange problem with events. I seems that Unity's compiler has a problem when it comes to default parameters.
I have an Event:
public static event System.Action<int> OnVisualLevelUp;
and I have a Function:
public static void LevelAchievement(int playerLevel, System.Action potentialAbordAction = null, bool autoLogin = false)
Then I do this:
LevelBar.OnVisualLevelUp += WK_GameCenter.LevelAchievement;
MonoDevelop complaints about that, but Unity does not, so I left it as is.
When the event is called, LevelAchievement does this and throws a NullReferenceException on the last line:
if (potentialAbordAction == null){
Debug.Log("potentialAbordAction is null");
return;
}
potentialAbordAction ();
It actually reaches the function call, not returning on the check. I fixed it by adding the missing parameters to the event, but how is this even possible?
I would be very satisfied if somebody could explain that to me :)
I think this might be correct -- just regular C# rules. System.Action<int> is the delegate, which specifies 1 parameter. Your levelAchievement only matches it by slicing off the Default parms. StackOverflow has some Qs on this.
Is your fixed version still using System.Action-int, or did you rewrite it to have all three parms?
I used all three. Thanks for the reply. I also thought that this is probably just a no go. Funny though, that Unity accepts it and compiles. but I created a bug report on this and it's uber investigation
Follow this Question
Related Questions
Initialize UnityEvent via script 1 Answer
Reloading Scene causes "null" object references. 3 Answers
Animations couldn't be found but still plays 0 Answers
Unsubscribe events in OnDisable causes NullReferenceException 2 Answers
Animation Crossfading and Events (Legacy) not triggering at times 0 Answers