- Home /
Why does my level progress reset after clicking the level menu button but doesnt reset after clicking the lvel menu button from the win screen?
I have a game with unlockable levels, and at lets say Level 3, when i win level 2, the level 3 button is unlocked. But when i go to main menu from pausing Level 3, all the buttons reset. Here is the code:
Level menu code:
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement;
public class LevelSelection : MonoBehaviour { public Button[] lvlButtons;
// Start is called before the first frame update
void Awake()
{
int levelAt = PlayerPrefs.GetInt("levelAt", 2);
for (int i = 0; i < lvlButtons.Length; i++)
{
if (i + 2 > levelAt)
lvlButtons[i].interactable = false;
}
}
}
Next level code:
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement;
public class MoveToNextLevel : MonoBehaviour { public int nextSceneLoad;
// Start is called before the first frame update
void Start()
{
nextSceneLoad = SceneManager.GetActiveScene().buildIndex + 1;
}
public void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "covek")
{
if (nextSceneLoad > PlayerPrefs.GetInt("levelAt"))
{
PlayerPrefs.SetInt("levelAt", nextSceneLoad);
}
}
}
public void Leveli()
{
SceneManager.LoadScene(nextSceneLoad);
}
}
Main menu code (for both buttons)
using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; using System.Collections;
public class levelmenu : MonoBehaviour { public void levelmeni() { SceneManager.LoadScene("Level Selections"); } }
Answer by rh_galaxy · Mar 15 at 09:20 PM
Three things might help you.
You need to save after SetInt() for it to take effect (I'm not sure if GetInt() will return the last set value or not if you don't do Save(), maybe it does, but if you exit the program without saving it will be lost)
PlayerPrefs.Save();
When you do PlayerPrefs.GetInt("levelAt") you should provide a default value if it doesn't exist, the doc doesn't say what happens if not, but I suspect it returns 0
PlayerPrefs.GetInt("levelAt", 0);
I would do the button interactable code like this so it's easier to see what it does, and be sure to set everything and not trust the values it has.
int levelAt = PlayerPrefs.GetInt("levelAt", 0);
for (int i = 0; i < lvlButtons.Length; i++)
{
lvlButtons[i].interactable = (i <= levelAt+1); //set true up to current level+1, else false
}