Question by
Glenstrover · Nov 11, 2019 at 12:39 PM ·
playerprefsmenulevels
User Playerprefs to save unlocked level
Hi
I am relatively new Unity and coding and am working on my first game and have been stuck on getting my levels menu to stay unlocked with PlayerPrefs for about 3 weeks now and could do with some help, could someone please point me in the right directions as nothing I try seems to work? My level button and Menu scripts are below.
public class LevelButton : MonoBehaviour
{
public LevelSelectMenu menu;
public Sprite lockSprite;
public Text levelText;
private int level = 0;
private Button button;
private Image image;
void OnEnable()
{
button = GetComponent<Button>();
image = GetComponent<Image>();
}
public void Setup(int level, bool isUnlock)
{
this.level = level;
levelText.text = level.ToString();
if(isUnlock)
{
image.sprite = null;
button.enabled = true;
levelText.gameObject.SetActive(true);
}
else
{
image.sprite = lockSprite;
button.enabled = false;
levelText.gameObject.SetActive(false);
}
}
public void OnClick()
{
menu.StartLevel(level);
}
}
public class LevelSelectMenu : MonoBehaviour
{
public int totallevel = 0;
public int unlockedLevel = 1;
private LevelButton[] levelButtons;
private int totalPage = 0;
private int page = 0;
private int pageItem = 18;
public GameObject nextButton;
public GameObject backButton;
void OnEnable()
{
levelButtons = GetComponentsInChildren<LevelButton>();
}
// Start is called before the first frame update
void Start()
{
Refresh();
}
public void StartLevel(int level)
{
//show player a level info or start the level
if(level==unlockedLevel)
{
unlockedLevel+=1;
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
Refresh();
}
}
public void ClickNext()
{
page+=1;
Refresh();
}
public void ClickBack()
{
page-=1;
Refresh();
}
public void Refresh()
{
totalPage = totallevel / pageItem;
int index = page * pageItem;
for(int i =0;i<levelButtons.Length;i++)
{
int level = index + i + 1;
if (level<=totallevel)
{
levelButtons[i].gameObject.SetActive(true);
levelButtons[i].Setup(level, level <= unlockedLevel);
}
else
levelButtons[i].gameObject.SetActive(false);
}
CheckButton();
}
private void CheckButton()
{
backButton.SetActive(page > 0);
nextButton.SetActive(page < totalPage);
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612214643im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How can I save values in an array using PlayerPrefs? 0 Answers
how to convert a dynamic playerpref to a dynamic int variable? 0 Answers
Bug with Lock Unlock System 0 Answers
How to make a menu for picking a level to play 2 Answers
PlayerPref doesnt work 2 Answers