- Home /
"If boolean X started being true on this frame, do Y" Is this possible in C#?
I've been looking around all day for a solution to this issue. It seems really basic and that's exactly why its so frustrating to not find a simple understandable answer.
All I want to do is in C#, make a piece of a script on an Update function run if a boolean started being true on the current frame.
Answer by getyour411 · Feb 08, 2014 at 01:53 AM
By defintion, Update() is run once per frame;
Update()
if(nowTrue) {
// do something cool
// could set nowTrue off
}
I don't think I understand. The update function is already assigning the boolean every frame. If I turn it off, the next frame will simply turn it back on.
Where do you see the Update function assiging the boolean every frame? All I wrote was a check for it to match your question "run something if a boolean started being true on the current frame".
The setting of the boolean to true could some from anywhere, a keypress, an external function, event, etc.
Answer by rutter · Feb 08, 2014 at 02:21 AM
Since Update is run once per frame, you can cache values to compare them between frames.
public class FooChecker : MonoBehaviour {
bool foo;
bool lastFoo;
void Start() {
lastFoo = foo;
}
void Update() {
//step 1: update values for this frame
foo = Random.value < 0.5f;
//step 2: check if values have changed
if (foo != lastFoo) {
if (foo) {
Debug.Log("Foo just became true on frame " + Time.frameCount);
} else {
Debug.Log("Foo just became false " + Time.frameCount);
}
}
//step 3: cache values for next frame
lastFoo = foo;
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613132855im_/https://answers.unity.com/themes/thub/images/avi.jpg)