Hello chaps, I’m trying to workout a simple light switch trigger. Whenever I push the button the Bool reverts back to the initial value (true) and the light stays on. Code below:
Looking at the debug I can see that the bool does change to false, and which then makes the child(light) become active again. Any thoughts would be handy, thanks.
Odds are that some other script (or another copy of this same script) is turning the light back on. When you press E once, do you get only a single debug message?
Edge-trigger values such as GetKeyDown() are only valid in Update().
OnTriggerStay is called from the Physics loop, and hence it gets called as much as FixedUpdate().
This means you have the opportunity to get multiple cycles through the OnTriggerState with the GetKeyDown() being true.
Instead, test for GetKeyDown() in an Update() function, and when you get that key, set a boolean that indicates a light state change must happen.
Over in the OnTriggerStay, if that boolean is true, toggle the light and then clear the boolean.
For more details on the calling order, see this diagram:
Note how there is a sub-loop through the Physics block that can take you through multiple times, whereas Update() is outside of this.
EDIT: Actually looking at your construct further, because you rely on the OnTriggerStay as a gating mechanism for even enabling the keyboard check, you will need to somehow backflow that condition out to Update so that you can’t just tap E, then run over and the instant you go inside the light it would turn on from the “stored” E press. You could also just clear it every time you find it set at the start of your Update() loop.
This, and the easiest way to do it is to set a boolean when the player enters/exits the trigger, and then checking for the key and the boolean in Update().
I don’t believe so, I’m pretty sure I’ve only got the one script involved but I’ll double check. Still it’ll be worth checking as I’m a bit daft. Thanks!
@Kurt-Dekker Thanks for the reply chap really helpful and interesting. I’ve now got that flowchart book marked! I’ll make some some and have a play about.
I’ve still clearly got a lot to learn. Thanks for taking the time!