Changing to a scene using it's buildIndex

Hello.

I’m new to unity and coding c# and I have a question about changing scenes.
In this game I have made I want to make a button on the final scene (buildIndex = 6)to go back to the first one(buildIndex = 0).

SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex - 6);

Doing this works fine but I was wondering if there was a way where you could directly change to a scene without having to add/subtract to the current.

Thanks in advance!

1 Like

Using the index number is (I think) an older way that is still supported.

It’s fragile because if you change the order by adding/removing a scene, everything breaks.

Instead just use the name!

1 Like

Have you tried

ceneManager.LoadScene(0);

But agreeing with Kurt… Name is better than index.

4 Likes

Thanks for the help but now I have a new question, how would I load a name. Taking a guess I’m assuming it would be:

SceneManager.LoadScene(*name*)

but I’m not sure.

Edit:
Nevermind I figured it out. For anyone wondering the line is:

SceneManager.LoadScene("menu");

Just change menu to your scene name.

4 Likes

thanks it worked

The Method you are using is the best, as, if you were to change the name of the scene
you would have to change it every where you used it and thats quite frustrating

thank you

ha