- Home /
Increment in while loop, with timeout
Hey guys, I did look all over the forums for an answer to this question, but found nothing :( The thing is, I have a function, that should increment a variable (X) in a while loop, something like this while (x<5){ x++; } The only problem is that the loop is carried out instantaneously (as it should), but I want the increment to be done once per frame rate (Time.deltaTime should be used I think), but I don't really know how can I set a delay to each incrementing. Any help would be appreciated! Many thanks
Answer by besttof · Apr 01, 2014 at 09:22 AM
You could use a timer variable and update that in the Update function like so:
public float delay = 1f;
private float timeout;
private float x;
void Update()
{
timeout -= Time.deltaTime;
if (timeout <= 0)
{
x++;
timeout += delay;
}
}
But it would probably be easier and more in line with your initial approach to use a coroutine:
public float delay = 1f;
void Start()
{
StartCoroutine(Foo(5));
}
IEnumerator Foo(int count)
{
int x = 0;
while (x < count)
{
x++;
yield return new WaitForSeconds(delay);
}
}
Both examples are C# btw, but should work equally well in UnityScript.
Thanks, I will try your solution when I reach home. the thing is I want everything to happen in the update() function. I am using unity script, but if you say it works, I'll try to add it and see what happens. The thing I need is to make it increment once with the frame rate in update (time.deltatime i think).
Hm, reading your question again, I think you might mean something like this:
public float stepSize = 3f;
void Update()
{
if (x < 5) x += Time.deltaTime * stepSize;
}
That will increment the value of x continuously over time, while my previous example will make x increase in discrete steps (i.e. not continuously). Is that what you wanted to know?
Not exactly, but I figured it out. I needed to increment a value if a certain condition is met, once per frame, until it reaches a value. I ended up using a while loop (to stop execution of anything else, thus not needing flags if the action started or not) and a co-routine function that increases the value. Nevertheless, many thanks for your help and effort!
Your answer
![](https://koobas.hobune.stream/wayback/20220613141654im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Problem with while statement. 1 Answer
Timed while loop? 0 Answers
A node in a childnode? 1 Answer
Blender Animation Looping Delay Problem 2 Answers
Audio loop after time 2 Answers