- Home /
On boolean becoming true, do something - how do I stop code activating over and over?
I'm trying to activate some code in the Update function to pick up an object when a boolean becomes true. However, the code at the minute continuously activates whilst the boolean is true, which causes the character to rapidly pick up and drop the object. Is there a way I could set it only to activate upon the boolean becoming true, and then not to activate again until the boolean becomes false, and true again? I would prefer to do it in the update function, otherwise a large chunk of code will have to change to work with GetComponents and SendMessages and the likes.
Thanks for your help!
Here is the script, although I'm not sure it's necessary for this:
if (zButton) { if (!hasObject) { //if the fiducial cant be seen, stop this script from picking up objects if (!renderer.enabled) { return; } if (Physics.Raycast(camera.main.transform.position, (transform.position-camera.main.transform.position), hit, 75, LayerMask)) { otherThing = hit.transform; if (otherThing.tag =="Moveable") { otherThing.rigidbody.isKinematic = true; otherThing.rigidbody.detectCollisions = false; otherThing.transform.position.z = 0; otherThing.parent = transform; otherThing.Find("Glowblock").light.enabled = true; hasObject = true; } }else { if (otherThing.tag == "Moveable") { otherThing.rigidbody.isKinematic = false; otherThing.rigidbody.detectCollisions = true;
transform.DetachChildren();
otherThing.transform.position.z = 0;
otherThing.Find("Glowblock").light.enabled = false;
hasObject = false;
//etc etc....
Answer by Joshua · Apr 24, 2011 at 04:18 PM
Ah, good question and it's important to do this as much as you can when scripting - to releive stress from the machine.
Your script now looks like:
var switch : Boolean;
function Update () {
if(switch) {do stuff;}
}
you want to have the script know if the boolean is true (or false) and if it has changed from the previous frame. So add a var that holds the old value of your bool:
var switch : Boolean; var oldSwitch : Boolean;
function Update () {
if(switch && switch == !oldSwitch) {do stuff; oldSwitch = switch;}
}
not that in the if function you turn the oldswitch var to hold the same value as the original boolean, so it won't be triggered again.
Cheers!
This answer is brilliant, and worked great, thanks. I have a few other places where I could make use of this.
I just stuck in an extra bit of code which makes oldSwitch become false when switch becomes false, and now i can call the script over and over but only when the boolean becomes true. Thanks!
Your answer
Follow this Question
Related Questions
Controlling multiple booleans 1 Answer
Switch code from Js to C# 1 Answer
switching the active boolean 1 Answer
Boolean check not referenced correctly from other script 2 Answers
Changing Missile Speed 1 Answer