So basically, I’ve decided to try and find my own way of unlocking levels.
This is my LevelsSelect.cs script:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
public class LevelSelect : MonoBehaviour {
public List<GameObject> levels = new List<GameObject>();
public static int buttonLoopCount;
public static int unlockedLevelCount = 0;
// Use this for initialization
void Start () {
if(PlayerPrefs.GetInt("Levels") == 0)
{
// How many levels are unlocked if this is true?
PlayerPrefs.SetInt("Levels", 0);
Debug.Log("Player has not unlocked any levels. Level 1, shall, however, be available.");
levels[0].GetComponent<Button>().interactable = true;
}
else if (PlayerPrefs.GetInt("Levels")>=1) {
// Hey hey hey, we've played before, alright! So, what happens now?
PlayerPrefs.GetInt("Levels");
for(int i = 0; i < PlayerPrefs.GetInt("Levels"); i++)
{
levels[i].GetComponent<Button>().interactable = true;
}
}
}
// Update is called once per frame
void Update () {
if(Input.GetKeyDown(KeyCode.D))
{
PlayerPrefs.DeleteAll();
}
}
// Handles the button event for each button
public void levelSelection(int i)
{
// Now that we've passed an int to this function, we can call levels with an index number to go by
// which can then determine if that level is unlocked.
if (levels [i].GetComponent<Button> ().interactable) {
// Because the build setings start at 0, add 2 to index (i) to begin a level 1
i = i + 2;
Debug.Log("Loading level ... " + i);
Application.LoadLevel(i);
}
}
}
The level selection works as it should, its just the intractable buttons. I’ve chosen to disable/enable them depending on whether the level is unlocked. But right now, I have a problem. IF the player goes and selects level 1, kills enemy, happy days, and then goes back to main menu, and back onto level select, level 2 button will not be intractable for some reason. At the moment, it only works if this happens:
Go to level select > Level 1 > Kill enemy > Back to level select > Back to level 1 > kill enemy again > back to level select. Only when that is done, will level 2 be unlocked. So basically, you have to player level 1 twice before level 2 is unlocked. HOWEVER, if I play level 1, 3 times, level 3 unlocks with no problem. (If it did have the same problem, I would have had to play level 1, 4 times before level 3 unlocked)
This is how I increment levels unlocked…
PlayerPrefs.SetInt("Levels", PlayerPrefs.GetInt("Levels") + 1);