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.