来自 bool setter 的火灾事件

fire event from bool setter

我正在尝试在布尔值实际更改时触发一个事件。我读到使用自定义设置和获取方法是执行此操作的方法之一。但我一直收到 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");
            }
        }           
    }
}

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