Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I wait for a scene to Unload?

When I click on a button it's calling in the On Click to the method ActivatePlayer:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class LoadSceneOnClick : MonoBehaviour
{
    private Scene scene;

    private void Start()
    {
        scene = SceneManager.GetActiveScene();
        StartCoroutine(WaitForSceneUnLoad(SceneManager.GetSceneByName("The Space Station")));
    }

    public IEnumerator WaitForSceneUnLoad(Scene scene)
    {
        return null;
    }

    public void ActivatePlayer()
    {
        SceneManager.UnloadSceneAsync(0);
        Cursor.visible = false;
        GameControl.player.SetActive(true);
    }
}

But now I want to wait for the UnloadSceneAsync to finish first this line:

SceneManager.UnloadSceneAsync(0);

Only when it finished to unload make the rest two lines:

Cursor.visible = false;
GameControl.player.SetActive(true);

The problem is when I click the button I still see for a second some gui elements of the scene index0. The scene in index is the main menu and when I click the button for a second even less of a second I see part of the main menu text. It seems like it's activating true the player before unloading the main menu finished. And since both scenes the main menu and the scene where the player is have cameras I see the main menu for a second.

like image 336
Daniel Lip Avatar asked Oct 20 '25 12:10

Daniel Lip


1 Answers

Try to put your script in IEnumerator

public void ActivatePlayer()
{
    StartCoroutine(StartActivatePlayer());
}

IEnumerator StartActivatePlayer()
{
   AsyncOperation ao = SceneManager.UnloadSceneAsync(0);
   yield return ao;
   Cursor.visible = false;
   GameControl.player.SetActive(true);
}

Hope it help.

like image 63
Alvin Avatar answered Oct 23 '25 00:10

Alvin