- Home /
Having trouble with slowly decreasing a variable
I've looked at some other peoples problems, but I just can't figure out what to fix exactly. My energy counter decreases too fast. I had a yield statement before that just made it pause for 2 seconds before decreasing really fast. I'm also having trouble stopping it once it hits 0. Unity decides to crash on me.
This is what I had before I had any issues with it other than it speeding fast:
var energy = 100;
function Start () {
}
function Update () {
guiText.text= energy.ToString();
Decrease();
Debug.Log(energy);
}
function Decrease()
{
while (energy>=0){
energy--;
}
Answer by Lo0NuhtiK · May 06, 2012 at 03:15 PM
Here's one way :
var energy : int = 100 ;
var depleteBy : int = 1 ; //deplete energy by this much
var depleteSeconds : float = 1.5 ; //deplete energy by 'depleteBy' after this many seconds
function Start(){
//start up a function that kicks off in depleteSeconds, then repeats every depleteSeconds afterward
InvokeRepeating("DepleteMe", depleteSeconds, depleteSeconds) ;
}
function DepleteMe(){
energy -= depleteBy ;
if(energy <= 0){
energy = 0 ;
CancelInvoke("DepleteMe") ; //end this repeater if out of energy
}
}
I can't tell if it's even working because now my update function isn't showing anything with the GUI text or Debug Log X_x
well, I didn't write your entire script to work by copy/paste... kinda figured you'd notice what was left out and know what you need to do to do whatever else you're wanting...
Oh I know. I added the update with the GUI text and stuff and it's just not showing up anymore in general. Lol. I'll figure it out.
Just add this at the bottom for a quick run :
function OnGUI(){
GUILayout.Box("Energy = : " + energy.ToString() ) ;
}
I got it to work :) Thank you!
$$anonymous$$y GUI Text on my scene disappeared for some reason so my script wasn't attached to anything, but I had it working lol. Thank you! :D
Answer by Piflik · May 06, 2012 at 03:15 PM
Change your Decreas function to the following:
function Decrease() {
if(energy > 0)
energy--;
}
Your problem was that you have a while loop in your function, so the first time it is called, it will decrease the energy to 0.
It's still going to decrease it every update call that way though.
But it won't decrease completely on the first update. And now yield WaitForSeconds() should work as expected.
Your answer
Follow this Question
Related Questions
Variable Question. [Simple] & [JS] 1 Answer
Variable decreases multiple times 0 Answers
Using a variable for decreasing health? 1 Answer