Unity- Load - Unlock levels and check if there are next levels existing

I am working on small game similar to angry birds since I am new to both unity and C#. I want to make load and unlock next level if all enemies are dead and check if new level exist (if not) return back to Level selection scene.

This is what I tried:

LevelScript

using UnityEngine; using
 UnityEngine.SceneManagement;

 public class LevelScript :
 MonoBehaviour {
 
 [SerializeField] string
_nextLevelName;

 Monster[] _monsters;




void OnEnable()
{
    _monsters = FindObjectsOfType<Monster>();
}


private void Update()
{
    int currentLevel = SceneManager.GetActiveScene().buildIndex ;
   

    if (currentLevel >= PlayerPrefs.GetInt("levelsUnlocked"))
    {
        PlayerPrefs.SetInt("levelsUnlocked", currentLevel );
    }

    if (MonsterAreAllDead())
    {

        GoToNextLevel();

    }

    Debug.Log("Level" + PlayerPrefs.GetInt("levelsUnlocked") + "UNLOCKED");
}







bool MonsterAreAllDead()
{

    foreach (var monster in _monsters)
    {
        if (monster.gameObject.activeSelf)
            return false;

    }

    return true;
}


void GoToNextLevel()
{
    Debug.Log("Go to next level" + _nextLevelName);
    SceneManager.LoadScene(_nextLevelName);


}
}

and Level Manager

public class LevelManager : MonoBehaviour
{
    int levelsUnlocked;
    public Button[] buttons;
    
    void Start()
    {
        levelsUnlocked = PlayerPrefs.GetInt("levelsUnlocked", 1);
        
        for (int i = 0; i < buttons.Length; i++)
        {
            buttons*.interactable = false;*

}
for (int i = 0; i < levelsUnlocked; i++)
{
buttons*.interactable = true;*
}
}

public void LoadLevel(int levelIndex)
{
SceneManager.LoadScene(levelIndex);

}
I have these 2 scripts and I attached both to canvas and my buttons. Also attached Level script to my levels.
Problem is that all levels gets unlocked at begin.
Also after completeing levels automatically It want to go to next level which is not exist yet.
Pls help me. Sorry if my question is stupid and for bad english.

You never do a save to make it stick.

PlayerPrefs.SetInt("levelsUnlocked", currentLevel );
PlayerPrefs.Save(); //needed

Also you may think about if you need to run this code in Update() (every frame it does this), at least you should skip the “>=” and change it to “>”.

if (currentLevel > PlayerPrefs.GetInt("levelsUnlocked"))

Can’t really see anything more that is wrong in the code you provided.

Do it like this:

 void GoToNextLevel()
 {

     Scene nextScene = SceneManager.GetSceneByName(_nextLevelName);


     if(SceneManager.sceneCount < nextScene.buildIndex){
           Debug.Log("Go to next level" + _nextLevelName);
           SceneManager.LoadScene(_nextLevelName);    
     }else{
          SceneManager.LoadScene("<Your Menu Scene Name>"); 
                                                               
     }
 
 
 }