Ramin Afshar
Ramin Afshar

Reputation: 1019

fire event from bool setter

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");
            }
        }           
    }
}

Upvotes: 0

Views: 102

Answers (1)

Servy
Servy

Reputation: 203812

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.

Upvotes: 3

Related Questions