using UnityEngine;
using UnityEngine.SceneManagement;
public class LevelScript : MonoBehaviour
{
private const string LevelsUnlockedKey = “levelsUnlocked”;
public void Pass()
{
int currentLevel = SceneManager.GetActiveScene().buildIndex;
Debug.Log("Current Level Index: " + currentLevel);
int levelsUnlocked = PlayerPrefs.GetInt(LevelsUnlockedKey, 1);
Debug.Log("Levels Unlocked before update: " + levelsUnlocked);
// Unlock the next level only if currentLevel is higher than previously unlocked levels
if (currentLevel >= levelsUnlocked)
{
PlayerPrefs.SetInt(LevelsUnlockedKey, currentLevel + 1);
PlayerPrefs.Save();
Debug.Log("Levels Unlocked updated to: " + PlayerPrefs.GetInt(LevelsUnlockedKey));
}
else
{
Debug.Log("No update to levelsUnlocked, currentLevel: " + currentLevel + " < levelsUnlocked: " + levelsUnlocked);
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class LevelManager : MonoBehaviour
{
int levelsUnlocked;
public Button[] buttons;
private void Start()
{
levelsUnlocked = PlayerPrefs.GetInt("LevelsUnlocked",1);
levelsUnlocked = Mathf.Clamp(levelsUnlocked, 1, buttons.Length);
for (int i = 0; i > buttons.Length; i++)
{
buttons[i].interactable = false;
}
for (int i = 0; i > levelsUnlocked; i++)
{
buttons[i].interactable = true;
}
Debug.Log("Levels Unlocked: " + levelsUnlocked);
}
public void LoadLevel(int LevelIndex)
{
SceneManager.LoadScene(LevelIndex);
}
private void OnEnable()
{
// Log PlayerPrefs when this script is enabled (e.g., returning to menu)
int levelsUnlocked = PlayerPrefs.GetInt("LevelsUnlocked", 1);
Debug.Log("Levels Unlocked when returning to menu: " + levelsUnlocked);
}
// Saves PlayerPrefs on application quit or pause
private void OnApplicationQuit()
{
PlayerPrefs.Save();
}
private void OnApplicationPause(bool pauseStatus)
{
if (pauseStatus)
{
PlayerPrefs.Save();
}
}
}