Next Level Using numbers

I’m trying to make a really simple script (because I’m still new to scripting) so when my 2D character enters the collider the next level will start. I’ve been literally working on this one script for 30-40minutes. I just need the script to work and for me to be able to edit the numbers in the editor so they can be used on each level and I don’t have to remake the script.

Script here:

function onTriggerEnter2D(other: Collider2D) {

SceneManagement.SceneManager.LoadScene(“”);

}

Once again, not good at scripting but I’m really trying here, any help would be great.

Do you mean something like this?

Create empty object with SceneLoader.cs script in first level (let’s call this level “scene_A”).

using UnityEngine;
using UnityEngine.SceneManagement;

public class SceneLoader: MonoBehaviour {
     public static SceneLoader instance;
    
     void Awake() {
        if(!instance) {
            instance = this;
        }
        else {
            DestroyObject(gameObject);
        }
        DontDestroyOnLoad(gameObject);
     }
    
    int currentLevel = 0; 

    static readonly string [] gameLevels = new string[] {
        "scene_A",   // 0
        "scene_B",  //  1
        "scene_C"  //   2
    };

	public void LoadNextLevel() {
        int nextLevelNuber = (currentLevel + 1) % gameLevels.Length;
        SceneManager.LoadScene(gameLevels[nextLevelNuber]);
        currentLevel = nextLevelNuber;
    }
}

Edit gameLevels array according to your needs.
Add your scenes into build settings.
When you want to start another game level call

SceneLoader.instance.LoadNextLevel();

in onTriggerEnter2D() methods or anywhere where you need.

Next level can be reached using:

SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex

  • 1);

Integrating in your script would look like this:

function onTriggerEnter2D(other: Collider2D) {

SceneManagement.SceneManager.LoadScene(SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1));

}

@TrePlaysGames:

You can easily do what your asking by ensuring that all scenes are in the build order and by extending your script just a little bit.

//This is the value you assign in the inspector.
public int mySceneToLoad;

function onTriggerEnter2D(other: Collider2D)
{
 SceneManagement.SceneManager.LoadScene(mySceneToLoad);
}

Hope this helps

This should work and give you a public variable in the editor:

var levelToLoad : int;

function OnTriggerEnter2D(other : Collider2D){
    SceneManagement.SceneManager.LoadScene(levelToLoad);
}

or a string instead of an int if you want to use names.

The reason it’s not working is also because of the function name not starting with a capital O. To check if something is running at all I always like to do a quick Debug.Log(“nameOfFunction”) when I try to figure out where the problem lies.

Thanks it works like a charm! I’ll go study more on this scripting too.