1

In this code, I click on button for level 1, and I play out level 1. Once I return back to the map, level 2 should be unlocked because I set the boolean to true when I pressed button 1.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class MainButtons : MonoBehaviour

{
  private bool level2Ready;
    private bool level3Ready;
    private bool level4Ready;
    private bool level5Ready;


 void Start()
    {
       level2Ready = false;
       level3Ready = false;
       level4Ready = false;
       level5Ready = false;
    }

public void Level1Map() { //button 1 in the map is pressed
      level2Ready = !level2Ready; // unlocks level 2 button
      SceneManager.LoadScene(0);
    }


public void Level2Map() { // level 2 button is pressed
      if (level2Ready == true) {
      SceneManager.LoadScene(4); //loads level 2 game scene
      level3Ready = true;
    }

}
Fredrik Schön
  • 4,888
  • 1
  • 21
  • 32

2 Answers2

0

The scene is loaded when you press the button. If this script is also in the Level2, then Start() is called once again when loading Level2 with SceneManager.LoadScene(0). This sets everything back to false. You need to persist the parent object of this script MainButtons (Assuming something like a scene or state manager).

You can do it with a call to Object.DontDestroyOnLoad

Yamuk
  • 750
  • 8
  • 27
0

Instead of having the state in your component (which may be reloaded, and reset) MainButtons, you can keep them in a static class:

For example something like...

public static class LevelReadyManager
{
    public static bool level2Ready;
    public static bool level3Ready;
    public static bool level4Ready;
    public static bool level5Ready;
}

and then your component would use them like this:

public class MainButtons : MonoBehaviour
{

    public void Level1Map() { 
        LevelReadyManager.level2Ready = !LevelReadyManager.level2Ready; 
        SceneManager.LoadScene(0);
    }


   public void Level2Map() { 
       if (LevelReadyManager.level2Ready == true) {
           SceneManager.LoadScene(4);
            LevelReadyManager.level3Ready = true;
      }
   }

}

Because we make them static, they not be instansiated and not dependent on any GameObject, thus persist even though you change scenes and unload/create new objects etc.

Fredrik Schön
  • 4,888
  • 1
  • 21
  • 32