Question Levels Locked/Unlocked

spicisco

New member
Joined
Jul 15, 2022
Messages
2
Programming Experience
Beginner
This level unlocking thing is really racking my brain. Last thing I like to do is ask for help.

My problem:
Staring the game, all my levels are locked except for Level 1. Which is obviously great. So I start level 1, which the object of the level is to gather 4 "soul fragments' to move to the next level. The script works and once 4 fragments are gathered it moves you to the next level. The problem is it not only unlocks level 2, but also unlocks levels 3 & 4. Clearing level 2, unlocks level 5, etc. So I'm assuming its unlocking 4 levels up from the current level you're on.

Soul Fragments Collected Script:
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using TMPro;
    using UnityEngine.SceneManagement;
   
   
    public class SFCollected : MonoBehaviour
    {
        private int fragments = 0;
        public int nextSceneLoad;
   
        [SerializeField] private TextMeshProUGUI fragmentsText;
   
        void Start()
        {
            nextSceneLoad = SceneManager.GetActiveScene().buildIndex + 1;
        }
   
        private void OnTriggerEnter2D(Collider2D collision)
        {
            if (collision.gameObject.CompareTag("Fragment"))
            {
                Destroy(collision.gameObject);
                fragments++;
                fragmentsText.text = "x " + fragments;
            }
   
            if (fragments is 4)
            {
                SceneManager.LoadScene(nextSceneLoad);
   
                if(nextSceneLoad > PlayerPrefs.GetInt("levelsUnlocked"))
                {
                    PlayerPrefs.SetInt("levelsUnlocked", nextSceneLoad);
                }
            }
        }
    }


LevelManager Script:
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.UI;
    using UnityEngine.SceneManagement;
   
   
    public class LevelManager : MonoBehaviour
    {
        int levelsUnlocked;
        public SceneFader fader;
        public Button[] buttons;
   
        void Start()
        {
            levelsUnlocked = PlayerPrefs.GetInt("levelsUnlocked", 1);
   
            for (int i = 0; i < buttons.Length; i++)
            {
                buttons[i].interactable = false;
            }
   
            for (int i = 0; i < levelsUnlocked; i++)
            {
                buttons[i].interactable = true;
            }
        }
   
        public void LoadLevel(int levelIndex)
        {
            SceneManager.LoadScene(levelIndex);
        }
   
        public void Select (string levelName)
        {
            fader.FadeTo(levelName);
        }
   
    }

Help is greatly appreciated!
 
Last edited:
Back
Top Bottom