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!