Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Changing to a scene using it's buildIndex

Discussion in 'Scripting' started by BenMasondev, Apr 1, 2020.

  1. BenMasondev

    BenMasondev

    Joined:
    Apr 1, 2020
    Posts:
    4
    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).

    Code (CSharp):
    1. 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!
     
    Martin3606 likes this.
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,520
    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!
     
    Kenan_Nynor likes this.
  3. BPPHarv

    BPPHarv

    Joined:
    Jun 9, 2012
    Posts:
    318
    Have you tried
    Code (CSharp):
    1. ceneManager.LoadScene(0);
    But agreeing with Kurt.. Name is better than index.
     
  4. BenMasondev

    BenMasondev

    Joined:
    Apr 1, 2020
    Posts:
    4
    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:
    Code (CSharp):
    1. SceneManager.LoadScene(*name*)
    but I'm not sure.

    Edit:
    Nevermind I figured it out. For anyone wondering the line is:
    Code (CSharp):
    1. SceneManager.LoadScene("menu");
    Just change menu to your scene name.
     
    Last edited: Apr 1, 2020
    Kenan_Nynor and Kurt-Dekker like this.
  5. vladiprogame

    vladiprogame

    Joined:
    May 22, 2021
    Posts:
    1
    thanks it worked
     
  6. craftyrite2011

    craftyrite2011

    Joined:
    Jan 16, 2022
    Posts:
    1
    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
     
  7. Chathuranga_Chandrasekara

    Chathuranga_Chandrasekara

    Joined:
    Mar 20, 2023
    Posts:
    1
    thank you

    ha