- Home /
Unity freezing on Waitforsecond
I'm trying to raise Canvas smoothly and Unity crashes on method call. I have : 1. Canvas Gameobject 2. Script thats calling method 3. Script with Method itself:
IEnumerator Fader(float sec)
{
eg_canvas.GetComponent<CanvasGroup>().alpha += 0.05f;
yield return new WaitForSeconds(sec);
}
void EG_canvas_start()
{
eg_canvas.SetActive(true);
eg_canvas.GetComponent<CanvasGroup>().alpha = 0;
while (eg_canvas.GetComponent<CanvasGroup>().alpha <= 1)
{
StartCoroutine(Fader(0.1f));
Debug.Log(eg_canvas.GetComponent<CanvasGroup>().alpha.ToString());
}
}
What I'm doing wrong? Thanks in advance.
Answer by eses · Sep 01, 2018 at 02:02 PM
Hi @CrPbI3yH
You'd want to run your coroutine only once - now you are running it in your while loop; as long as alpha is less than or equal to 1, you are starting your coroutine.
You should just start your Fader coroutine once, and do something like this in your Fader coroutine:
IEnumerator Fader(float duration)
{
alpha = 0f;
var cg = eg_canvas.GetComponent<CanvasGroup>();
while (alpha <= 1f)
{
alpha += Time.deltaTime / duration;
cg.alpha = alpha;
yield return null;
}
}
void EG_canvas_start()
{
eg_canvas.SetActive(true);
StartCoroutine(Fader(10f));
}
sorry, but I don't see pause here. how waitforsecond must be implemented here? something like this? while (eg_canvas.GetComponent().alpha <= 1) { eg_canvas.GetComponent().alpha += Time.deltaTime; new Waitforseconds(sec); } yield return null;
@CrPbI3yH - You will have to explain - at least I don't get what you mean by Pause? Do you mean, you don't want to start fading, then fade from point A to point B - that is what my example will do. You didn't mention a word about pausing.
I meant that i don't see Waitforseconds in your code.
Don't do this:
while (eg_canvas.GetComponent<CanvasGroup>().alpha <= 1)
{
StartCoroutine(Fader(0.1f));
Debug.Log(eg_canvas.GetComponent<CanvasGroup>().alpha.ToString());
}
Do this ins$$anonymous$$d:
StartCoroutine(Fader(0.1f));
Debug.Log(eg_canvas.GetComponent<CanvasGroup>().alpha.ToString());
When you have started a coroutine, it will do all stuff asynchronously, every time it reaches yield
instruction, the coroutine execution is paused and then resumed in next frame/fixedUpdate/amount of seconds deter$$anonymous$$ed by WaitForSeconds(), etc. It's done automatically. The coroutine will resume itself everytime and will do next step in the while
/do
/foreach
or any other loop instruction. There's no need to start the coroutine using another one loop instruction, as you did in while (eg_canvas.GetComponent<CanvasGroup> ().alpha <= 1) { StartCoroutine(Fader(0.1f)); }
.
In your code you're starting a hundred of identical coroutines, since every Update() is called every 0.016 seconds when fps is 60 frames, and all of these coroutines are trying to increase the alpha value, that's quiet overwhel$$anonymous$$g for the Unity and for the CPU to do such things. That's why Unity freezes.