- Home /
Problems with unlocking levels
In the menu I put an option for the levels to be unlocked as I pass them. In this case, once passed, I can choose the level that I already passed. At the moment I have 10 levels. To give an example, it happens to me that when I choose to start from level 5 and go to level 6, the following are blocked. From 7 to 10 they are blocked and I have to unblock them again. How could I modify the code so that once it is unlocked it does not lock again? Here is the script i'm using:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class LevelSelector : MonoBehaviour
{
public Button[] levelBTN;
public SceneLogic sceneLogic;
void Start()
{
//To unlock levels
int level = PlayerPrefs.GetInt("level", 1);
for (int i = 0; i < levelBTN.Length; i++)
{
if (i + 1 > level)
levelBTN[i].interactable = false;
}
}
public void levelToLoad(int level)
{
SceneManager.LoadScene(level);
}
public void ButtonPressed1()
{
sceneLogic.IndiceDeNiveles = 0;
PlayerPrefs.SetInt("CorrespondingLevel", sceneLogic.LevelsIndex);
}
public void ButtonPressed2()
{
sceneLogic.IndiceDeNiveles = 1;
PlayerPrefs.SetInt("CorrespondingLevel", sceneLogic.LevelsIndex);
}
public void ButtonPressed3()
{
sceneLogic.IndiceDeNiveles = 2;
PlayerPrefs.SetInt("CorrespondingLevel", sceneLogic.LevelsIndex);
}
public void ButtonPressed4()
{
sceneLogic.IndiceDeNiveles = 3;
PlayerPrefs.SetInt("CorrespondingLevel", sceneLogic.LevelsIndex);
}
public void ButtonPressed5()
{
sceneLogic.IndiceDeNiveles = 4;
PlayerPrefs.SetInt("CorrespondingLevel", sceneLogic.LevelsIndex);
}
public void ButtonPressed6()
{
sceneLogic.IndiceDeNiveles = 5;
PlayerPrefs.SetInt("CorrespondingLevel", sceneLogic.LevelsIndex);
}
public void ButtonPressed7()
{
sceneLogic.IndiceDeNiveles = 6;
PlayerPrefs.SetInt("CorrespondingLevel", sceneLogic.LevelsIndex);
}
public void ButtonPressed8()
{
sceneLogic.IndiceDeNiveles = 7;
PlayerPrefs.SetInt("CorrespondingLevel", sceneLogic.LevelsIndex);
}
public void ButtonPressed9()
{
sceneLogic.IndiceDeNiveles = 8;
PlayerPrefs.SetInt("CorrespondingLevel", sceneLogic.LevelsIndex);
}
public void ButtonPressed10()
{
sceneLogic.IndiceDeNiveles = 9;
PlayerPrefs.SetInt("CorrespondingLevel", sceneLogic.LevelsIndex);
}
}
I should create a function that if it is 10 levels and I choose level 5, it should check if levels 6 to 10 are locked or unlocked. If they are unlocked, I should leave them unlocked if I go to 6. And if they are locked, I should leave them locked. Any idea how to do that?
Answer by Darkluca · Apr 08, 2021 at 08:01 AM
You are setting the Playerprefs int but not getting it again.
Code something like:
if(PlayerPrefs.GetInt("CorrespondingLevel") == *wanted level*)
{
//unlock code
}