x


Increase/Decrease Over Time, Not Frames

Hello,

Just to clear things up, I want to know an easy way to increase, or decrease a value over time (seconds) as apposed to the frame.

So normally, if I wanted to increase a value, I would just do value++ in the update, which increases the value every frame. What about every second? Is there an easy way to do that within an update?

Thanks

more ▼

asked Jan 23 '12 at 12:09 AM

oliver-jones gravatar image

oliver-jones
2.5k 207 226 257

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

There is a simple value that translates between seconds and frames. If you want to increment a floating-point number evenly over time, you can use

number += Time.deltaTime;

Over one second it will increase by one.

However, if you want to increment an int exactly once a second, you can use a coroutine:

int incrementThis = 0;

IEnumerator NumberIncrementer(ref int number)
{
    while(true)
    {
        yield return new WaitForSeconds(1);
        number++;
    }
}

void Start()
{
    StartCoroutine(NumberIncrementer(ref incrementThis));
}

void Update()
{
    Debug.Log(incrementThis);
}

This way it will increment the number exactly once a frame.

more ▼

answered Jan 23 '12 at 12:18 AM

syclamoth gravatar image

syclamoth
15k 7 15 80

InvokeRepeating would be simpler, and slightly more accurate and efficient.

Jan 23 '12 at 12:23 AM Eric5h5

@Eric5h5 - Can InvokeRepeating be placed in an Update?

Jan 23 '12 at 12:31 AM oliver-jones

The point of InvokeRepeating is that it's not Update, it repeats at given intervals.

Jan 23 '12 at 01:46 AM Eric5h5

InvokeRepeating needs to use string reflection to get a method name, and you can't pass paramaters into the method in question. It is a little less versatile because of this.

Jan 23 '12 at 02:39 AM syclamoth
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x588
x92
x47
x38
x28

asked: Jan 23 '12 at 12:09 AM

Seen: 1194 times

Last Updated: Jan 23 '12 at 02:39 AM