user3623628
user3623628

Reputation:

How to only execute code after 5 seconds?

So, in Unity I have this Hunger code that subtracts a little each time.

#pragma strict

var Hunger:float;
var MaxHunger:float=100;
var timer:float;

function Start () 
{
    Hunger=MaxHunger;
}

function Update () 
{
    timer+=Time.deltaTime;
    if(timer>=10) 
    {
    Hunger-=1.0;
    }
}

My problem is that I only want 1 to be subtracted from Hunger every five seconds. I already tried setting it to take off 0.2 every second, but it doesn't work. I just need it to wait for five seconds before subtracting 1. Thanks!

Upvotes: 1

Views: 1837

Answers (1)

Chris McFarland
Chris McFarland

Reputation: 6169

You could use the InvokeRepeating method:

function SubtractHunger ()
{
    Hunger -= 1.0;
}

function Start () {
    Hunger = MaxHunger;
    var seconds:int = 5;
    InvokeRepeating("SubtractHunger", seconds, seconds);
}

// and then you don't need the Update function

Or, you could use a timeLastSubtracted variable or similar to check within your Update function:

var timeLastSubtracted:float;

function Update ()
{
    if (Time.time >= timeLastSubtracted + 5) {
        Hunger -= 1.0;
        timeLastSubtracted = Time.time;
    }
}

Upvotes: 1

Related Questions