I need help with my level unlocking script

I am making a game and no matter what I do I cannot get my level select to make new level buttons interactable. Only lvl one will be interactable, I am able to beat the level and advance to the next one by pressing the “next level” button, but when i go back to menu level 2 still isnt interactable…

I have 2 scripts, one for the level select menu, and a sceneloader script( i will only include the level advance part of that script, but if you want to see the whole thing feel free to ask)

level select:

public Button[] lvlButtons;

    // Start is called before the first frame update
    void Start()
    {
        int levelAt = PlayerPrefs.GetInt("levelAt", 2);

        for(int i = 0; i < lvlButtons.Length; i++)
        {
            if (i + 2 > levelAt)
                lvlButtons[i].interactable = false;
        }
    }

SceneLoader:

    public int nextSceneLoad;

    void Start()
    {
        nextSceneLoad = SceneManager.GetActiveScene().buildIndex + 1;
    }

    public void Advance()
    {
        if(SceneManager.GetActiveScene().buildIndex == 4)
        {
           Debug.Log("You Win!");
        }
        else
        {
            SceneManager.LoadScene(nextSceneLoad);

            if (nextSceneLoad > PlayerPrefs.GetInt("levelAt"))
            {
                PlayerPrefs.SetInt("levelAt", nextSceneLoad);
            }
        }

       
    }

Add Debugging. But from what I can see, if nextSceneLoad doesn’t start at a value of at least 3 then you will never call PlayerPrefs.SetInt, which means PlayerPrefs.GetInt will never return a value other than the default of 2 Output what all these values actually are, verify you are actually calling SetInt. etc

cna you explain that a little more please? i dont understand

Can you just add your debugging? What happens all depends on what values are returned from GetInt, if you are calling SetInt at all, what index the currently loaded scene is, etc, and you’re providing no information for any of that and making anyone look at this just guess at it all. Just output all that.

I think what Uncle Joe is suggesting is this:

I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run?
  • what are the values of the variables involved? Are they initialized?

Knowing this information will help you reason about the behavior you are seeing.

1 Like

Also, to guard against typos with your PlayerPrefs key, this is my favorite pattern:

Here’s an example of simple persistent loading/saving values using PlayerPrefs:

Useful for a relatively small number of simple values.