0
\$\begingroup\$

I'm a beginner in Unity, I wrote a script that will load the next scene whenever monsters in a scene are dead. The script is working fine. Here's my script.

public void Update()
{
    if (MonstersAreAllDead())
        GoToNextLevel();

}

  

//Loads The next Level After all the monsters are Confirmed Dead

private void GoToNextLevel()
{
    SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);

   
} 

However, I only have two scenes in my game and When Unity gets to the final scene, it displays an error since there is not next scene to load to.

Scene with build index: 2 couldn't be loaded because it has not been added to the build settings.
To add a scene to the build settings use the menu File->Build Settings...
UnityEngine.SceneManagement.SceneManager:LoadScene (int)
LevelController:GoToNextLevel () (at Assets/Scripts/LevelController.cs:39)
LevelController:Update () (at Assets/Scripts/LevelController.cs:30)

My question. How do I tell unity that it should stop trying to load the next scene and instead Display a message to the user? The message displayed can be something like "This is the final scene".

Thank you all in advance for your answers.

\$\endgroup\$
0

1 Answer 1

1
\$\begingroup\$

This is pretty trivial. Just take the number of the scene you want to go to, and then compare it against the number of scenes you built. If the number is at or above the limit, don't load that scene.

private void GoToNextLevel()
{
    int nextSceneIndex = SceneManager.GetActiveScene().buildIndex + 1;

    if (nextSceneIndex < SceneManager.sceneCountInBuildSettings) {

        // If we have a next scene to load, load it.
        SceneManager.LoadScene(nextSceneIndex);

    } else {

        // Otherwise, display your "you win" message.
        gameCompletedMessage.SetActive(true);
    }   
} 

Don't forget to read the documentation to find helpful parts of the API like sceneCountInBuildSettings.

\$\endgroup\$
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .