I'm trying to create a level loader system in unity that will load a level based on the button you press. The code I have now is extremely unnecessary as I have to create an IEnumerator and a StartCoroutine function for each individual button.
This is the code I have so far:
public void LoadLevel1()
{
StartCoroutine(Level1());
}
IEnumerator Level1()
{
transition.SetTrigger("Start");
yield return new WaitForSeconds(2);
SceneManager.LoadScene("Level 1");
}
This process for each level gets really annoying and repetitive as 10 levels already takes up over 150 lines of messy code.
I tried to optimize this by loading the scene with the name of the button.
For example on the button that loads level 1, the name of the button is called "Level 1", so logically I would just call "gameObject.name" and take the name of the button "Level 1" and load the scene "Level 1".
Visual Studio doesn't have a problem with this but when I try to run the code below:
public void LoadLevel()
{
StartCoroutine(GoToLevel());
}
IEnumerator GoToLevel()
{
transition.SetTrigger("Start");
yield return new WaitForSeconds(2);
SceneManager.LoadScene(gameObject.name);
}
But for some reason, unity takes gameObject.name and says, "Oh you want the name of your parent" and tries to load the scene "LoadLevel". Which is nonexistent because it's supposed to load "Level 1". I have no idea why this is happening. Any ideas would be appreciated.