Locking and Unlocking Levels in Unity


 

Progression in the games often involves unlocking new levels as players achieve specific goals or complete challenges. In Unity, this can be achieved by controlling the state of levels using scripts and PlayerPrefs.



Here are a few Steps to Locking and Unlocking Levels


Setting Up the Project


1- Create the Levels: Design and create the your levels as you want. Each level should be in a separate scene in Unity.


2- UI Buttons: Create UI buttons for each level in your main menu or level selection screen.




LevelSelector Script


Create a C# script called LevelSelector and attach it to your level selection buttons(each button when clicked it load different scene). This script will handle level unlocking based on player progress. Here's an example of the LevelSelector script:




 

public class LevelSelector : MonoBehaviour
{
    public int level;
    void Start()
    {
        // Lock all buttons except level 1 at the beginning
        if (level > 1 and !IsLevelUnlocked(level))
        {
            GetComponent<Button>().interactable = false; 
} } public void OpenScene() { SceneManager.LoadScene("Level " + level.ToString()); } public static bool IsLevelUnlocked(int levelIndex) { return PlayerPrefs.GetInt("Level" + levelIndex + "_Unlocked", 0) == 1; } }
  • LevelSelector script is attached to UI buttons for level selection.


  • Start(): Locks buttons for levels greater than 1 if the level is not unlocked.


  • OpenScene(): Loads the corresponding level scene when the button is clicked.


  • IsLevelUnlocked(int levelIndex): Checks if a level is unlocked based on PlayerPrefs. Returns true if the level is unlocked (value is 1 in PlayerPrefs).



The line return PlayerPrefs.GetInt("Level" + levelIndex + "_Unlocked", 0) == 1; is a conditional statement that checks whether a specific level is unlocked in the game. Let's break it down:

1- PlayerPrefs.GetInt("Level" + levelIndex + "_Unlocked", 0):


  • PlayerPrefs.GetInt(key, defaultValue) is a method in Unity's PlayerPrefs system that retrieves the integer value associated with the specified key.
  • In this case, the key is dynamically generated based on the levelIndex. For example, if levelIndex is 1, the key becomes "Level1_Unlocked". This key represents whether Level 1 is unlocked in the game.
  • If the specified key doesn't exist in PlayerPrefs (which would be the case if the level is not unlocked yet), the method returns the defaultValue, which is 0 in this scenario.

2- == 1:

  • After retrieving the value using PlayerPrefs.GetInt(), the script compares it with 1.
  • If the retrieved value is 1, it means the corresponding level (specified by levelIndex) is unlocked. The == 1 comparison checks if the stored value for the level is set to 1.
  • If the comparison is true, the function returns true, indicating that the level is unlocked. If it's false, the function returns false, indicating that the level is locked.


In summary, this line of code checks the PlayerPrefs system for a specific key indicating whether a level is unlocked. If the key exists and has a value of 1, the level is considered unlocked, and the function returns true. If the key doesn't exist or has a value other than 1, the level is considered locked, and the function returns false.




Write Your Conditons 

I will write a code and then explain it, I think this is better.

In this script.





public class Ground : MonoBehaviour
{
    [SerializeField] private TextMeshProUGUI scoreText;
    [SerializeField] private AudioClip scoresound;

    private int score = 0;

    void Start()
    {
        // Reset level completion status when the game starts
        PlayerPrefs.DeleteAll();
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.CompareTag("Box"))
        {
            sound.Instance.PlaySound(scoresound);
            score++;
            UpdateScoreText();

            // Check score milestones and unlock corresponding levels
            if (score == 5 && SceneManager.GetActiveScene().name == "Level 1")
            {
                // Unlock Level 2 when score reaches 5 in Level 1
                PlayerPrefs.SetInt("Level2_Unlocked", 1);
                PlayerPrefs.Save();
                Debug.Log("Level 2 Unlocked!");

                // Load Level 2
                SceneManager.LoadScene("Level 2");
            }
        }
    }


Explanation:


We handle the unlocking of levels based on the player's score milestones(this is an example just for explenation you can use any condition). Let's break down how it works:


  • Resetting Level Completion: At the start of the game (Start() method), we reset all level completion statuses using PlayerPrefs.DeleteAll(). This ensures a fresh start every time the game is launched.


  • Checking Score Milestones: When the player collides with an object tagged as "Box", their score increases. We then check specific score milestones (score == 5, score == 10, etc.) for the active level using SceneManager.GetActiveScene().name.


  • Unlocking Levels: When a score milestone is reached, the script unlocks the next level. For example, when the score reaches 5 in "Level 1", it unlocks "Level 2". This is done by setting the corresponding PlayerPrefs key (Level2_Unlocked, Level3_Unlocked, etc.) to 1, indicating that the level is now accessible.


  • Loading Unlocked Levels: After unlocking a level, the script loads the corresponding scene using SceneManager.LoadScene(...), allowing the player to progress to the next level in the game.




This script provides a flexible way to control level progression, making it easy to extend the game with additional levels and score-based challenges. Players can enjoy a sense of achievement as they unlock new content by reaching specific score goals, enhancing their overall gaming experience.





Happy coding




Previous Post Next Post

Contact Form