How to load a scene based on the name of the script's parent gameObject?

Viewed 28

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.

1 Answers

gameObject.name take the value from gameobject in which you added your script. You have to pass btn's gameobject.name and it will working fine. Alternatively you can add a argument in function with int and pass level's index like this :

public void LoadLevel(int i)
{
    StartCoroutine(GoToLevel(i));
}

IEnumerator GoToLevel(int i)
{
    transition.SetTrigger("Start");

    yield return new WaitForSeconds(2);

    SceneManager.LoadScene("Level" + i);
}

Call this LoadLevel function from btn and pass level's number as a argument in inspector and you good to go. And Make Sure to keep the scene's name as Level1, Level2 ....

Related