0

I've been developing a basic game in Unity and am attempting to write code to detect whenever a ball has 'stopped' moving (i.e. movement is effectively zero). I was hoping to achieve this by sampling the difference between the balls locations over a number of frames inside the position changed event handler, passing through the difference between two movements through the eventargs.

However whenever I try to access the locations array I get this error: A field initializer cannot reference the non-static field, method, or property 'Ball.locations'

I'm slightly confused as to what specifically is occurring, as I'm rather new to event handlers and admittedly copied the bottom lambda (because it looked tidier) without really understanding what exactly it is doing.

Here is the relevant code:

public class Ball : IBall {
    private float[] locations = new float[5];

    public Ball() {

    }

    public Vector3 Position {
        get { return position; }
        set {
            if (position != value) {
                BallMovedEventArgs eventArgs = new BallMovedEventArgs (position, value);
                position = value;
                OnMove (this, eventArgs);
            }
        }
    }

    public event EventHandler<BallMovedEventArgs> OnMove = (sender, e) => {
        // error is thrown here
        if(locations.Length > 5) {
            Debug.Log("Too many location deltas!");
        }
    };
}

Thanks for taking the time to read my post, any help in understanding what is happening here is much appreciated!

1 Answers1

0

See this error description. You can't use locations.length in the EventHandler. You are defining both this event handler and the locations array at the 'same' time. It seems like this if statement isn't needed anyhow. The length of 5 is constant.

Community
  • 1
  • 1
bgura
  • 860
  • 15
  • 33
  • 1
    I read through that question and wasn't sure but I just looked at the MSDN link at the bottom of the best answer and I believe I understand it now. In my code `OnPositionChanged` isn't a function but a variable like `locations` and since they're both declared at the 'same' time they can't depend on each other? – James Neill May 13 '17 at 05:41
  • 1
    And also, now that you point it out, yes that comparison is completely pointless. – James Neill May 13 '17 at 05:43
  • Yes, and yes. You probably want something like an `index` which keeps track at which point to insert the next location. If `index` is beyond the size of `locations` >= 5 then you log your error – bgura May 13 '17 at 05:49