Counting down in seconds opposed to frames

I’ve been having a browse on here for a while and haven’t come up with a way to fix my script. Basically I have an energy bar for a flashlight, it works fine but it counts way too quick, I was wondering how I could slow it down so that I can use seconds instead of frames. If I set the number for the flashenergy to 600 or so the energy bar works correctly but it starts to make the game lag.

public static var flashon: int = 0;
public static var flashlevel: float = 0;

function Start () {
    light.enabled = false;
}

function Update() {
    if (Input.GetKeyDown("f")) {
        audio.Play();
        if (light.enabled == true)
            light.enabled = false;
        else
            light.enabled = true;
        flashon = 1;
    }
    if (flashlevel == 100){
        light.enabled = false;
    }
    if (light.enabled == false){
        flashon = 0;
    }
    if (flashon == 1){
        if (flashlevel <100)
            flashlevel += 1;
        InvokeRepeating ("Countdown", 1.0, 1.0);
    }
    if (flashon == 0){
        if (flashlevel >0)
            flashlevel -= 2;
        InvokeRepeating ("Countdown", 1.0, 1.0);
    }
}

Any help would be much appreciated.

I guess i know where your lags are comming from. You you even understand what InvokeRepeating does? It runs the specified function automatically in the interval you specified (in your case every second). But you start another one of these calls every frame. So at 60 fps after 1 sec there are 60 InvokeRepeatings running at the same time and the number is growing endless in your case.

Furthermore, where is your “Countdown” function and what is it doing?

Like syclamoth already mentioned you should increment / decrement your float by Time.deltaTime which is the current frame time ( 1 / fps ). So if your game runs at 100 frames per sec. deltaTime will be 0.01. If you add this value every frame to a variable, it adds up to exactly 1.0 after 1 sec.

edit btw: usually you count down when the flashlight is on… It works of course both ways, but usually that value represents the available energy, or not? In your case it’s more like a overheating value which is a bit strange for a flashlight :wink:

Also avoid == comparisons with float values 100.002312 is not the same as 100.000000