How to link buttons to individual levels within the same scene?

Hi,

I’m using Unity to build a game but I want to add a start screen to it, with buttons for Level 1, Level 2, Level 3 and Level 4. I want the buttons, once pressed on, to go straight to that level and if the player passes it, to continue on with the next randomly generated levels. (I’m basing the game off the Unity 2D Roguelike Tutorial)

using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement; // Allows SceneManager to be used.
 
public class LoadSceneOnClick : MonoBehaviour
{
 
    public void LoadByIndex(int sceneIndex) // Passes in what scene will be loaded.
    {
        SceneManager.LoadScene(sceneIndex); // SceneManager loads scene.
    }
}

This is my code for my LoadSceneOnClick script that I am using for each of my main menu buttons. I got this from the Creating A Main Menu tutorial. However it is not working because it assumes that each level is a different scene. This game contains all its levels in a single scene so I’m not sure how to make this work. I’ve tried passing in the variable for level instead of sceneIndex but it did not work, so maybe I was not doing it right.

Any help would be appreciated!!

Thanks :slight_smile:

I don’t know what the Roguelike Tutorial is, but if you have multiple Levels in one Scene, you could achieve what you want to do like:

public void LoadByIndex(int levelIndex) 
{
    PlayerPrefs.SetInt("initialLevel", levelIndex); // Store which level in the loaded scene will be played
    SceneManager.LoadScene("yourSceneName"); // SceneManager loads scene.
}

And then in your scene with the 4 levels, have some sort of LevelController, which (e.g. in the Start()-Method) does something like:

int i = PlayerPrefs.GetInt("initialLevel");
// TODO start the level identified by i --> Set Player's initial position to level i's position, spawn enemies in level i, etc...