timer using Time.deltaTime not working outside Update()

For some reason after I put the timer -= Time.deltaTime in a separate method it stopped working altogether. The CastSpell gets called in Update and all works fine, except for the timer part. If I were to just take it out and stick it in Update by itself it works no problem. I have also tried subtracting or adding any number to it but it just doesn’t budge.
I’d like to keep the timer in the CastSpell method so I can create different spells and not have 50 timers all separated.

this is the code I’m using. I call it in update and add a float and button in the parameters.

    private void CastSpell (float timer, Button spellButton)
    {
        timer -= Time.deltaTime;

        if(timer <= 0f)
        {
            spellButton.interactable = true;
        }
        else { spellButton.interactable = false; }
    }

If anyone knows a solution or a workaround I’d be glad to hear it.

timer wont go down if you call this function ,

lets assume your “float timer” is 20 ,
everytime you call the function it will do (20 -= Time.deltaTime);

it will never go down since the float timer which you always insert is 20

AH I see, any idea how to omit this because I’m kinda stumped. It’s not the biggest problem but it would’ve been nice to have everything done in one method instead of having 10 timers running at all times.

Yes, do it with an Coroutine, something like this:

        private IEnumerator CastSpell(float timer, Button spellButton)
        {
            spellButton.interactable = false;
            yield return new WaitForSeconds(timer);
            spellButton.interactable = true;
        }
2 Likes

Your passing your timer by value. If the timer is in the same script as Update then should just use that variable instead of passing. If not then you would have to do it by reference.

CastSpell(ref timer);

void CastSpell(ref float timer)
{

}

They all must be individual unless all spells are on the same cooldown. If not maybe group spells by slots like

float[] spellTimer = new float[9]; // [0] <-> [8]
spellTimer[i] -= Time.deltaTime;
1 Like
CastSpell(ref timer);

void CastSpell(ref float timer)
{

}

This worked like a charm! I have no idea what the ref variable actually changed but this is perfect!

The IEnumerator way also works but it’s not really the thing I was looking for as it doesn’t show the timer in game, it just counts it down.

Thank you all for helping a dude out!

When you pass a variable without a keyword it is passing by value meaning that it has no association with the variable you passed. With ‘ref’ you are referenced to the point of memory that holds the variable and not just a copy of its contents.

1 Like

Wow that’s very good to know! You saved me a couple days of coding and a bunch of headaches with a three letter word!