- Home /
Finding change in variable between updates
I would like to work out the change in a variable from the last update. so something like x(i+1) - x(i) but in a c# way. I am pretty new to c# so any help would be great! I can't use the built in mouse position and getaxisraw etc because the x and y data is not coming from the mouse. Hope this makes sense to someone!
you mean like storing the previous value in a class variable?
public class Difference : $$anonymous$$onoBehaviour {
private float previousValue = 0;
private void Start () {
previousValue = ... // set it to wherever you get the value
}
private void Update () {
currentValue = ... // wherever it comes from - you didn't share this info
float difference = currentValue - previousValue;
previousValue = currentValue; // so that you can compare the next time Update() is called
}
}
Answer by TheKnightsofUnity · Jul 24, 2018 at 12:06 PM
Hello @KateHassan,
The thing you are looking for is properties and delegates.
public event Action<int> OnVariableChanged = delegate { };
public int X
{
get
{
return x;
}
set
{
int oldValue = x;
int newValue = value;
//Here you can find out difference
x = value;
OnVariableChanged.Invoke(value);
}
}
This way you can keep on track when a variable, for example, is changing in the set block and in the more elegant way using delegates like:
private void Awake()
{
OnVariableChanged += OnVariableChangeHandler;
}
private void OnVariableChangeHandler(int value)
{
//Do something when variable change
}
Please feel free to ask any questions you might have.
All the best, The Knights of Unity
Hello, thank you for your reply. I still don't really understand how this gives me the change in x? At the moment I have: public float eyex, eyey, eyeconfidence; public void ReceiveData(float x, float y, float confidence) { eyex = x; eyey = y; eyeconfidence = confidence;
Vector2 ComputeDisplacement() {
Vector2 retvalue = new Vector2(deltaeyex, deltaeyex);
return retvalue;
}
and I am trying to find deltaeyex
I think the above solution might be more complex than what you would like to do. Basically it will call the function you specify in the delegate whenever the value changes.
If you are changing the value in Update() method, you can write something like this:
private void Update()
{
float oldEyeX = eyeX; //store actual value of eyeX variable
eyeX = 7; //$$anonymous$$odify eyeX value
float deltaX = eyeX - oldEyeX;
}
Hi, apologies I am still confused! I don't know what I put in for eyeX = 7 as I don't know the eyeX value until the game is running. Does this make sense? I need the difference between eyex in frame 1 and eyex in frame 2 etc..?? $$anonymous$$ate