0

I'm trying to fire an event when a bool has actually changed value. I read that using a custom set and get method is one of the ways to do this. But I keep getting NullReferenceException: Object reference not set to an instance of an object

Public class Ball : MonoBehaviour {
public delegate void ballEvents();
public static event ballEvents OnBallStop;

private bool _previousValue = true;
private bool _ballStopped = true;
public bool BallHasStopped {
    get {return _ballStopped;}
    set {
        _ballStopped = value;
        if (_ballStopped != _previousValue){
            _previousValue = _ballStopped;
            if(value == true) {
                print("stop");
                OnBallStop(); // this causes the error
            } else {
                print("moving");
            }
        }           
    }
}
Ramin Afshar
  • 989
  • 2
  • 18
  • 34
  • 2
    As a side note, you do not need to keep `_previousValue` - before you do the assignment to `_ballStopped`, you've got the previous value in `_ballStopped`, and new value in `value` - so you can just have `if (_ballStopped != value) { _ballStopped = value; doWhatever(); }` in the setter. – Luaan Jan 16 '15 at 16:59

1 Answers1

3

When an event has no handlers it is null, and so cannot be invoked. You can check for null and not invoke it unless there are handlers.

Servy
  • 202,030
  • 26
  • 332
  • 449