tomytoms
tomytoms

Reputation: 1

Start highest unlocked level(scene) on button click

Im new in developing so need some help for my game! On my game I have 2 buttons one is "Play" and other "Level Select" I stuck at the "Play" button, need to make a script that is always loading the highest level that is unlocked, not current but highest. Here is the code that im using for level manager

public List<Button> levelButton;
public Sprite lockimage;

public bool delete;

private void Start()
{

    int saveIndex = PlayerPrefs.GetInt("SaveIndex");
    for (int i = 0; i < levelButton.Count; i++)
    {


        if (i <= saveIndex)
        {
            levelButton[i].interactable = true;
        }
        else
        {
            levelButton[i].interactable = false;
            levelButton[i].GetComponent<Image>().sprite = lockimage;
        }
    }
}
public void LevelSelect()
{
    int level = int.Parse(EventSystem.current.currentSelectedGameObject.name);
    SceneManager.LoadScene(level);
}

public void PlayGame()
{

    //code here

}

public void ResetGame()
{

    PlayerPrefs.SetInt("SaveIndex", 0);
    SceneManager.LoadScene(0);

}

public void DontResetGame()
{

    SceneManager.LoadScene(0);

}

}

Upvotes: 0

Views: 71

Answers (1)

IkerG
IkerG

Reputation: 51

 SceneManager.LoadScene(PlayerPrefs.GetInt("SaveIndex"));

edit: adding some info/context.

I realized that you set level buttons interactivity on the start functions based on the int save_index value you get from PlayerPrefs.

From there, I assumed that you could load the level directly using that same value on the PlayGame function.

Do note that the code I wrote will throw an error, if the "SaveIndex" key is not yet on PlayerPrefs

Upvotes: 1

Related Questions