- Home /
Changing Scenes Efficiently
I am making a game, and it has around 32 levels. i have a scene which has a button, with the number level, eg a button with 1, and so on. at the moment i have a Script which loads the scene if the button is pressed, but having to write out 32 different voids going between each scene is a real hassle, is there a way i could do this better? This is the script that is for the buttons: using UnityEngine; using UnityEngine.SceneManagement;
public class GameMaster : MonoBehaviour
{
public void GoToGameScene()
{
SceneManager.LoadScene("Level01");
}
public void Restart()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
public void GoToMainMenu()
{
SceneManager.LoadScene("MainMenu");
}
public void LevelSelect()
{
SceneManager.LoadScene("LevelSelect");
}
}
the level select void is the scene with all the buttons. this is what it looks like
i know it doesnt look the best, but its for testing purposes
Answer by haizathaneefa · Jun 19, 2020 at 02:57 AM
I am not sure if this is the best but create a function that gets the number from each button, something like:
string number;
public void getNumber()
{
number = gameObject.GetComponent<Text>().text;
}
and then make a function to load the level while referencing your number level
public void ChangeLevel()
{
SceneManager.LoadScene(number);
}
you need to change a bit the string, right ? Like
string number;
public void getNumber()
{
number = "Level"+(gameObject.GetComponent<Text>().text);
}
Because @Symbie seems to use a nomenclature like "level" + level's number
In any case, "number" must be equals to targeted scene's name
Thank you so much @haizathaneefa and @SiniKettu_ using both of your answers got me exactly what i wanted!
Answer by Saiansh2525 · Jun 19, 2020 at 03:50 AM
I suggest that you use build index. Press build settings and add all your scenes in order and they will have a build index. Never use strings in scene management. Here is a link to that: https://docs.unity3d.com/ScriptReference/SceneManagement.Scene-buildIndex.html
Next, you should assign the function to each and every button with a Button parameter and just take the button's text convert it to a number and load the level with build indexes accordingly.