0

So I'm trying to create a level system somewhat like in angry birds where after you complete one level next one is unlocked and so on.

So to get which all levels are unlocked I used playerPref.GetInt and a for loop to make these buttons interactable. But im getting an Index out of bound error for my **LevelsUnlocked **Loop I dont know why Totally unsure why it's happening, any ideas? (Probably something stupid because I'm a bit of a noob).

public class LevelManager : MonoBehaviour
{
    int LevelUnlocked;

    public Button[] Buttons;
    void Start()
    {
        LevelUnlocked = PlayerPrefs.GetInt("LevelUnlocked", 1);

        for(int i = 0; i < Buttons.Length; i++)
        {
            Buttons[i].interactable = false;

        }

        for (int i = 0; i < LevelUnlocked; i++)
        {
            Buttons[i].interactable = true;

        }

    }

}
amal
  • 1
  • 2
  • 2
    Well, the obvious answer would be that `LevelUnlocked` is larger than `Buttons.Length`. What is the actual value? – Retired Ninja Jan 06 '23 at 07:33
  • Please share your logs. I.E. copy and paste your error, share the result of `LevelUnlocked = PlayerPrefs.GetInt("LevelUnlocked", 1);` and the length of `Buttons[i]` – Display name Jan 06 '23 at 07:38
  • This is the error message IndexOutOfRangeException: Index was outside the bounds of the array. LevelManager.Start () (at Assets/Scripts/LevelManager.cs:25) and the length of Button is 3 – amal Jan 10 '23 at 12:35

1 Answers1

0

I cannot be 100% sure without seeing your exact error message but Index out of bounds means that you tried to access an array with a integer that is either too small or too large.

You should make sure that public Button[] Buttons; has more elements than LevelUnlocked

This code should fix your issue:

public class LevelManager : MonoBehaviour
{
    int LevelUnlocked;

    public Button[] Buttons;
    void Start()
    {
        LevelUnlocked = PlayerPrefs.GetInt("LevelUnlocked", 1);

        for(int i = 0; i < Buttons.Length; i++)
        {
            Buttons[i].interactable = i<LevelUnlocked;

        }
    }
}

Also, be aware that arrays start at 0. So in, Button[] Buttons = new Button[3]; the first button is Buttons[0], the second is at Buttons[1] and so on. Calling Buttons[3] would provide an Index out of bounds error.

Display name
  • 413
  • 3
  • 14