My C# code is not working as planned. Please help. (Level Unlocking)
Hi, I am fairly new to programming and I have one error/issue that I can not fix that I have spent 2 days straight trying to figure out. To give you a summary of what I am talking about, I am making a game where you unlock levels as you go for example level one is unlocked in the beginning but if you complete level 1 the level 2 button in the level select menu will be enabled and you can play level 2 etc. Everything works fine like you can reach all the way to level 7 etc. but when you replay a level like say you have unlocked the levels all the way to 7 and you decide to replay level 1, all the progress will get removed so if you complete level 1 only level 2 and level 1 is available, same if you replay level 3 and complete it all levels above 4's progress will be removed. I would be so grateful if someone could tell me how I can fix and edit my code so that it unlocks the levels as you go but you can still replay any level without the removing of any progress. So here is my 2 sets of code (More Info: I have 7 levels level 1 starts at "2" in the build index, there is a main menu, a level select, the levels and then credits. Its a block game where you are a block and you dodge other blocks, the scenefader script is just a script that fades between scenes.) :
using UnityEngine; using UnityEngine.SceneManagement;
public class LevelCompleted : MonoBehaviour {
public string nextLevel = "Level02";
public int levelToUnlock = 2;
public void LoadNextLevel()
{
PlayerPrefs.SetInt("levelReached", levelToUnlock);
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
}
}
using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement;
public class LevelSelector : MonoBehaviour {
public SceneFader fader;
// The buttons I added to a game object where I had 7 slots and I dragged in my buttons.
public Button[] levelButtons;
void Start()
{
int levelReached = PlayerPrefs.GetInt("levelReached", 1);
for (int i = 0; i < levelButtons.Length; i++)
{
if (i + 1 > levelReached)
{
levelButtons[i].interactable = false;
}
}
}
public void Select(string levelName)
{
fader.FadeTo(levelName);
}
}
Answer by ErikHallmarkDev · May 16, 2017 at 09:49 PM
I'd be willing to bet that when you complete a level you're setting your levelReached variable directly, I'd suggest you check to make sure that levelReached isn't greater than the current level index first.
If that isn't the problem, could you please share the code that unlocks the levels?
I have already solved the problem but thank you for your comment.