Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

Level unlock

Discussion in 'Scripting' started by yusofazizi1955, May 5, 2019.

  1. yusofazizi1955

    yusofazizi1955

    Joined:
    Mar 23, 2019
    Posts:
    1
    I am new to unity and I have finished my first game, but I am stuck in level unlock system.
    I have created this level unlock system, but the problem is whenever I have unlocked more than 2 or all the levels and I go back and play the first level, then all the other levels become locked again. Can anyone please help me.






    Code (CSharp):
    1. public int LeveltoUnlock = 2;
    2.  
    3.  
    4.  
    5. public void Levelwon()
    6.     {
    7.  
    8.  
    9.         PlayerPrefs.SetInt("levelReached", LeveltoUnlock);
    10.        
    11.  
    12.  
    13.  
    14.     }


    Code (CSharp):
    1. public Button[] levelButtons;
    2.  
    3.     private void Start()
    4.     {
    5.         int levelReached = PlayerPrefs.GetInt("levelReached", 1);
    6.  
    7.         for (int i = 0; i < levelButtons.Length; i++)
    8.         {
    9.             if (i + 1  > levelReached)
    10.  
    11.             levelButtons[i].interactable = false;
    12.         }
    13.     }
     

    Attached Files:

  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    8,273
    That's because you're not storing the highest level reached; you're storing the last level finished (which you nonetheless call "levelReached").

    To make your variable name accurate, you only want to change it to a higher value, never a lower one:

    Code (CSharp):
    1. public void Levelwon() {
    2.      if (PlayerPrefs.GetInt("levelReached") < LeveltoUnlock) {
    3.           PlayerPrefs.SetInt("levelReached", LeveltoUnlock);
    4.      }
    5. }
     
    angrypenguin and Ryiah like this.
  3. hippocoder

    hippocoder

    Digital Ape Moderator

    Joined:
    Apr 11, 2010
    Posts:
    25,828
    Deleted bogus poll. Please don't do that.
    Moved to scripting.

    Try to put in more effort when asking for help and you'll get better responses.