how to change a value over time
so i would like to minus a value (i.e. 50) within 0.0166667 second, i have tried startcoroutine in update(not accurate), in while loop (it end in 0 second) and also invoke method in while loop(blow my pc up) . this is the code of the start coroutine in while loop.
float x = 50, length = 0.0166667, g;
bool b = true;
void Update()
{
g = Time.time;
while (x>0)
{
StartCoroutine(Tt());
}
if(x == 0 && b == true)
{
Debug.Log(g);
b = false;
}
}
IEnumerator void Tt()
{
x -= 1;
yield return new WaitForSeconds(length / 50);
}
so this will give g =0 in debug.log, which is in accurate, and i am not sure whether it is the problem of Time.time or my code.
0.0166667 seconds = 1/60 seconds
Unless your game runs quicker than 60 FPS, you could simply set the value to 0 after one frame.
Otherwise, yes, your code is completely messed up to do what want
It all depends on the performances of your game. Coroutines and the Update method can't be called quicker than once per frame.
Answer by Tulula · Mar 17, 2021 at 05:16 PM
I managed to get a result using the code below. There were a few errors. Float values such as length need 'f' to be placed at the end to signify a float - length = 0.0166667f; IEnumerator does not require void return type, simply IEnumerator Tt() works.
I used a while loop in the enumerator to check if x > 0 and if so the minus 1 and yield.
float x = 50, length = 0.0166667f, g;
bool b = true;
void Start()
{
StartCoroutine(Tt());
}
void Update()
{
g = Time.time;
if (x == 0 && b == true)
{
Debug.Log(g);
b = false;
}
}
IEnumerator Tt()
{
while (x > 0)
{
x--;
yield return new WaitForSeconds(length / 50);
}
}
do you mean you can get 0.0166667f when Debug.Log(g); is executed?
No not quite, what I got was 0.08 something but that is most likely due to the performance of my machine, it is not the best nor worst so there could easily be a delay.
Your answer
Follow this Question
Related Questions
nothing called after WaitForSeconds 1 Answer
Show image then wait for x seconds and hide it again. 0 Answers
Performance Issue with Coroutines 2 Answers
IENumerator does not work 0 Answers
Instantiate an object and destroy it after given time 2 Answers