Unity Freezes After SceneManager.LoadSceneAsync
Hi people!
So I'm trying to make a loading screen, with a breathing "loading" text. Here's how I implemented it before:
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class SceneLoader : MonoBehaviour
{
private Text _loadText;
// Use this for initialization
private void Start ()
{
_loadText = GameObject.Find("Text").GetComponent<Text>();
}
// Update is called once per frame
private void Update ()
{
StartCoroutine("LoadScene");
}
private IEnumerator LoadScene()
{
var prevScene = PlayerPrefs.GetInt("prevScene");
print(prevScene);
yield return new WaitForSeconds(3);
print("Loading scene now! BOOM");
var async = SceneManager.LoadSceneAsync(prevScene == 0 ? 1 : 0);
while (!async.isDone)
{
var lerp = Mathf.PingPong(Time.time, 1f);
_loadText.color = Color.Lerp(Color.black, Color.white, lerp);
}
yield return async;
}
}
The problem with this script is that Unity freezes to death after it starts the loading process. Currently my workaround (not exactly) is just avoid it and use SceneManager.LoadScene instead. The scene loads like in 4 seconds so it there's got to be something wrong with the code. Can anyone help me out? Thanks in advance!!!
Answer by MaskedMouse · Apr 21, 2017 at 04:38 PM
Thats because you don't have a yield in your while loop :P also not sure that Mathf.pingpong will work that way you want it to (don't know pingpong out of mind but Time.time is something I doubt).
The author of the question is right, his loading screen will work, if unity doesn't freeze game at 90%.
no actually he's completely correct that the reason it's freezing is because he has a loop in an IEnumerator without any yield statements, and he's also correct about the PingPong and time.Time not going to work in the way he wants them to so jokes on you pal.
He is calling StartCoroutine ("LoadScene"); in the Update () function.
Answer by Mana-Tech_Dev01 · May 21, 2020 at 10:04 AM
Not yielding from within the loop is definitely a problem, but the real problem is that even with yielding it still freezes. It goes from 0 to 0.9 directly with a freeze of few solid seconds in between. In other words, it looks like Unity is choking even if the coroutine is responsive.