- Home /
Difference of between a member variable and a instant variable in a coroutine
class Class1 : MonoBehaviour
{
...
float var1;
...
IEnumerator Coroutine1()
{
var1 = 0f;
float var2 = 0f;
float t = Time.unscaledTime;
while(var1 < 100f)
{
var1 += (Time.unscaledTime - t);
var2 += (Time.unscaledTime - t);
Debug.Log("var1 : " + var1 + " var2 : " + var2);
yield return new WaitForSeconds(Time.fixedDeltaTime);
t = Time.unscaledTime;
}
}
...
}
In this situation, The values of var1 and var2 are different.
I'm giving the same operation to var1 and var2, so why are there different values?
(Sorry for my bad English)
Is there something else changing the value of var1 perhaps?
By the way, waiting for fixedDeltaTime in a coroutine (which gets updates at deltaTime intervals) seems rather odd to me. What are you trying to achieve there?
There's only one difference which is whether the variable is member variable or instant variable.
I tried to make a function where the value was not affected by the timeScale and was decreasing regularly.
(I'm a beginner at Unity, so I don't know if this is a good idea.)
This code is only an excerpt which is relevant to my question.
(I'm sorry for my poor English once again.)
Answer by nicholasw1816 · Dec 08, 2018 at 07:33 PM
The member variable is stored, when the Coroutine updates, it will (- time) from it's previous value the last time it was updated. The instance value will refresh back to 0 or (null) each Coroutine update.
Well... I solved this problem.
It was very foolish mistake. The coroutine has been called several times because of a hole in my code.
Anyway, thank you for your answer.
This answer is wrong, it seems to be suggesting that every time the coroutine gets an update, it goes back to the start of the function (which would defeat the whole point of a coroutine). In fact, both variables are set to zero at the same point, outside the loop.