Using the ++ operator doesn't increment the scene on button click

On the LoadNextScene method why won’t the ++ operator work for incrementing the scene? My novice brain doens’t understand the difference.

This works:

 public void LoadNextScene()
{
    int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
    SceneManager.LoadScene(currentSceneIndex + 1);
}

This doesn’t:

public void LoadNextScene()
{
    int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
    SceneManager.LoadScene(currentSceneIndex ++);
}
1 Like

Hi Derrick,

It depends where you use the ++ operator. At the moment you are using it after the variable, so in your LoadScene method you are passing the value of currentSceneIndex before it is incremented.

To resolve the issue, use the ++ operator before the variable, that way it will be incremented before the value of the variable is used by the LoadScene method;

public void LoadNextScene()
{
    int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
    SceneManager.LoadScene(++currentSceneIndex);
}

Hope this helps :slight_smile:


See also;

3 Likes

Thanks Rob! Makes perfect sense now.

1 Like

Happy to help :slight_smile:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms