- Home /
How can i keep making the SendMessage repeat as long as the boolean is true
I have a kind of energy bar where when i collect enough i can instantiate an object, but i want the the energy to drain over time for as long as that object is alive.
I can make it reduce it once but struggling to make it repeat, pretty sure i'd be doing something in the if(orbAlive == true){ guiRef.SendMessage("SetFocus", spentAmount)); line i've tried a few things and still no success, so my question is how can i make the value of spentAmount be subtracted every second
var spentAmount : float = 1;
var particle:GameObject;
private var guiRef:GameObject;
private var orbAlive: boolean = false;
function FireAndReload (){
if(GameObject.Find("__GameMaster").GetComponent(Score).focus >= 5){
//Instantiate stuff in in here then setting the boolean true
orbAlive = true;
}
if(orbAlive == true){
guiRef.SendMessage("SetFocus", spentAmount));
}
if(GameObject.Find("__GameMaster").GetComponent(Score).focus <= 0){
orbAlive = false;
Destroy(particle);
}
}
}
Answer by ExTheSea · May 16, 2013 at 06:31 PM
The direct answer would be to do this:
function FireAndReload(){
....
if(orbAlive == true){
InvokeRepeating("EverySecond", 1.0, 1.0); //Calls EverySecond every second
}
...
}
function Update(){
{
if(orbAlive == false)
CancelInvoke("EverySecond"); //Stops EverySecond
}
...
}
function EverySecond(){
guiRef.SendMessage("SetFocus", spentAmount));
}
but i would recommend you to maybe let the script you send the message to handle the EverySecond part. Using SendMessage every second is not very performance-friendly.
Warning: This code is untested.
Hope it works for you.
bah i can make it deduct once it becomes active but i cant stop it lol
So your problem now is that EverySecond isn't stopped getting called? Do you ever set orbAlive to false?
Your answer
![](https://koobas.hobune.stream/wayback/20220613102403im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Check how long a bool has been true 2 Answers
Returning bool from another script (Cannot implicitly convert type 'void' to 'bool') 2 Answers
Delay Player From Using Action Button For A Period Of Time 0 Answers
Log a quickly changing value without boolean flags 0 Answers
SendMessage and boolean... my GO doesn't keep the value. 2 Answers