- Home /
NullReferenceException when call an event
Hi everyone :)!
I have a countdown float that is used for a wavespawner:
private float _countdown = 0;
public delegate void OnCountdownDelegate();
public event OnCountdownDelegate OnCountdownChange;
public float countdown{
get{
return _countdown;
}
set{
if(value < 0){
_countdown = 0;
}
else{
_countdown = value;
}
OnCountdownChange();//<--- The error says this does not exist yet (?
}
}
But when i start the game it says the following:
NullReferenceException: Object reference not set to an instance of an object
WaveSpawner.set_countdown (Single value) (at Assets/Scripts/Managers/WaveSpawner.cs:27)
WaveSpawner.Awake () (at Assets/Scripts/Managers/WaveSpawner.cs:39)
The error points the event i call when the countdown is setted. And when this happens the script auto-disables himself. But when i enable the script manually everything goes fine! I have this exact code but for money and no error appears.
Send help please! P.D. Thanks.
Answer by tadejP · Aug 05, 2017 at 06:48 AM
Event is always null if no functions are subscribed to it. Just add a null check:
if (OnCountDownChange() != null)
OnCountDownChange();
@tadejP Omg thank you!! I've been thinking all day in what could it be. I'm still new at program$$anonymous$$g. You saved my life! :D
Your answer
Follow this Question
Related Questions
How to make event trigger with custom events?? 1 Answer
How to unsubscribe from a delegate that is inside of a singleton? 2 Answers
Chartboost didCompleteRewardedVideo event not working 0 Answers
Subscribe to an event when the application is loaded 3 Answers
Making Multiple Switches Affect Different GameObjects 0 Answers