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--;

}

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 
   }
}

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.