- Home /
Call a function repeatedly while a boolean is true
I have a variable: boolean, that under certain conditions turns from false (default value) to true for a limited time and then automatically it goes back to false.
While it's true (eg for 5''), I want a function to be called repeatedly (this function makes an SM2 sprite appear and disappear fast, as an eye candy)
Using the following lines, doesn't work:
function Start (){
while (myBoolean == true){
InvokeRepeating("MyEyeCandyFunction",0,0.4);
}
}
What am I doing wrong? Thanks :-)
Answer by Mike 3 · Mar 09, 2011 at 08:15 PM
Just return from your eye candy function if the boolean is false
function Start (){ InvokeRepeating("MyEyeCandyFunction",0,0.4); }
function MyEyeCandyFunction() { if(!myBoolean) { return; }
//your code
}
If you want it to stop invoking it when the boolean has turned false:
function Start (){ InvokeRepeating("MyEyeCandyFunction",0,0.4); }
function MyEyeCandyFunction() { if(!myBoolean) { CancelInvoke("MyEyeCandyFunction"); return; }
//your code
}
Thanks so much $$anonymous$$ike. I had no idea I could use "return". Where can I read about it's use? (Searching the script reference I did not find anything).
$$anonymous$$ost program$$anonymous$$g sites/books - it's a general concept. It basically just returns the execution back to the function that called it (in this case, something in the unity engine), though you can use it to return an object back too (That's how nearly all of the unity functions give you data back)
Answer by DaveA · Mar 09, 2011 at 08:07 PM
var lastCheck = 0.0; var checkInterval = .4;
void Update() { if (myBoolean && (Time.time - lastCheck) >= checkInterval) { MyEyeCandyFunction(arguments); lastCheck = Time.time; } }
This will call MyEyeCandyFunction the first time myBoolean goes true, and then every checkInterval seconds thereafter until myBoolean goes false
Thanks very much DaveA, I marked $$anonymous$$ike's answer as accepted, because I found it more simple. Your suggestion gave me some ideas I could use in other occasions though :)
Answer by Tuck · Mar 09, 2011 at 07:28 PM
Put your code in an if statement inside of Update. It will be called every frame. For example:
void Update()
{
if(myBoolean)
{
MyEyeCandyFunction(arguments);
}
}
You will need to keep track of how many times your eye candy function is called and then set myBoolean to false after a certain amount of calls. If you don't want this to be called every frame check against Time.time to see how often to call it. I am in a rush but post a comment if you want me to get more in detail.
Thanks Tuck, but this doesn't help me much. "myBoolean" is automatically changed back to false, so I want this change to trigger the ceasing of my eye candy function repeated call.