Search Unity

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:
    9,859
    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. }
     
  3. hippocoder

    hippocoder

    Digital Ape

    Joined:
    Apr 11, 2010
    Posts:
    29,723
    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.
     
  4. Perturbator858

    Perturbator858

    Joined:
    Jan 21, 2021
    Posts:
    7
    Thank you so much