来自bool setter的火灾事件

时间:2015-01-16 16:53:56

标签: c# events

当bool实际改变了值时,我试图触发事件。我读到使用自定义set和get方法是执行此操作的方法之一。但我一直在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");
            }
        }           
    }
}

1 个答案:

答案 0 :(得分:3)

当事件没有处理程序时,它是null,因此无法调用。您可以检查null,除非有处理程序,否则不会调用它。