- Home /
How to freeze frame until it finishes loading?
I have this level generator MonoBehaviour that has a lot of loops and stuff going on inside... I still hadn't finished it, however, i think that this process may be too big to load in just one frame, (it's supposed that every time I hit a button it generates again everything) so I was thinking, is there a way in which I can freeze or pause the game in order to finish the level generating process (and not crash) and maybe get like an opaque screen while loading?
Answer by Ermiq · Dec 09, 2019 at 08:32 AM
I see two options:
Put the heavy code into a coroutine. This option is for the case where you'd prefer the game to keep running during the heavy process.
bool isLoadingHeavyStuff;
void Start() {
StartCoroutine(GenerateSomeHeavyStuff();
}
IEnumerator GenerateSomeHeavyStuff() {
while (isLoadingHeavyStuff) {
for (int i=0; i<thingsToLoadCount; i++) {
//do something with one of the things
//and take a pause till the next frame with the 'yield' instruction
yield return null;
//the game will continue to run, but this code will be paused
}
//once everything is done, stop the 'while' loop by setting condition to 'false'
isLoadingHeavyStuff = false;
}
}
Second option is to load a new scene (loading screen) as an overlay upon the main game scene:
isLoadingHeavyStuff; //flag that needs to be set to 'true' while you load something heavy
void Update() {
if (isLoadingHeavyStuff) {
var currentScene = SceneManager.GetActiveScene();
if (currentScene != SceneManager.GetSceneByName("LoadingScreenScene")) {
SceneManager.LoadScene("LoadingScreenSceen", LoadSceneMode.Additive);
Time.timeScale = 0; //pause the game
}
}
else { //if not loading
var currentScene = SceneManager.GetActiveScene();
if (currentScene == SceneManager.GetSceneByName("LoadingScreenScene")) {
SceneManager.UnloadSceneAsync("LoadingScreenSceen");
Time.timeScale = 1f; //resume the game
}
}