I am working on a game that will have a level lock and unlock system. Now I realize that most people will not choose to go back and replay a level that they have already passed through. But I have noticed a glitch with my games level lock and unlock system where if you go back and play a previous level and don’t win or if the game gets closed then the program will lock the next level again which had been previously unlocked. I tried moving the level unlocking into a load screen that would work between the levels to prevent this from happening but that did not work. I am not sure why. If anyone has any ideas on how to fix this it would be greatly appreciated.
Here is the code for my Main Menu Script and Level Control Script below:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class MainManuControlScript : MonoBehaviour {
public Button level02Button, level03Button;
int levelPassed;
// Use this for initialization
void Start () {
levelPassed = PlayerPrefs.GetInt ("LevelPassed");
level02Button.interactable = true;
level03Button.interactable = false;
switch (levelPassed) {
case 1:
level02Button.interactable = true;
break;
case 2:
level02Button.interactable = true;
level03Button.interactable = true;
break;
}
}
public void levelToLoad (int level)
{
SceneManager.LoadScene (level);
}
public void resetPlayerPrefs()
{
level02Button.interactable = false;
level03Button.interactable = false;
PlayerPrefs.DeleteAll ();
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class LevelControlScript : MonoBehaviour {
public static LevelControlScript instance = null;
GameObject levelSign, gameOverText, youWinText;
int sceneIndex, levelPassed;
// Use this for initialization
void Start () {
if (instance == null)
instance = this;
else if (instance != this)
Destroy (gameObject);
levelSign = GameObject.Find ("LevelNumber");
gameOverText = GameObject.Find ("GameOverText");
youWinText = GameObject.Find ("YouWinText");
gameOverText.gameObject.SetActive (false);
youWinText.gameObject.SetActive (false);
sceneIndex = SceneManager.GetActiveScene ().buildIndex;
levelPassed = PlayerPrefs.GetInt ("LevelPassed");
PlayerPrefs.SetInt ("LevelPassed", sceneIndex);
}
public void youWin()
{
if (sceneIndex == 3)
Invoke ("loadMainMenu", 1f);
else {
if (levelPassed < sceneIndex)
PlayerPrefs.SetInt ("LevelPassed", sceneIndex);
//levelSign.gameObject.SetActive (false);
youWinText.gameObject.SetActive (true);
Invoke ("loadNextLevel", 1f);
}
}
public void youLose()
{
//levelSign.gameObject.SetActive (false);
gameOverText.gameObject.SetActive (true);
//Invoke ("loadMainMenu", 1f);
}
void loadNextLevel()
{
SceneManager.LoadScene (sceneIndex + 1);
}
void loadMainMenu()
{
SceneManager.LoadScene ("MainMenu");
}
}