- Home /
Everytime when i start at level 3 or higher after completing it it goes back to level 2 how do i fix this?
I made a game from a tutorial on youtube and i have an level selection scene after you press play but know when i go to level 3 or higher from that level selection scene and i complete that level i am goin back to level 2 but when i start at level 1 or 2 i just go to the right scenes.
All my levels are called Level1 Level2 Level3 Level4 etc.
so this code should work.
public class LevelController : MonoBehaviour
{
private static int _nextLevelIndex = 1;
private Enemy[] _enemies;
private void OnEnable()
{
_enemies = FindObjectsOfType<Enemy>();
}
void Update()
{
foreach(Enemy enemy in _enemies)
{
if (enemy != null)
return;
}
Debug.Log("You killed all enemies");
_nextLevelIndex++;
string nextLevelName = "Level" + _nextLevelIndex;
SceneManager.LoadScene(nextLevelName);
}
}
Here is the code for my level selection scene i dont think the problem is on this code
public class lvlControl : MonoBehaviour
{
public void selectScene()
{
switch (this.gameObject.name)
{
case "Level1":
SceneManager.LoadScene("Level1");
break;
case "Level2":
SceneManager.LoadScene("Level2");
break;
case "Level3":
SceneManager.LoadScene("Level3");
break;
case "Level4":
SceneManager.LoadScene("Level4");
break;
case "Level5":
SceneManager.LoadScene("Level5");
break;
case "Level6":
SceneManager.LoadScene("Level6");
break;
case "Level7":
SceneManager.LoadScene("Level7");
break;
case "Level8":
SceneManager.LoadScene("Level8");
break;
}
}
}
it all worked fine until i went from 4 to 8 levels and know it doesnt work anymore.
I hope someone knows how to fix this and i would really appreciate if you reply to this.
_nextLevelIndex value at the start is always 1 and will always be 2 when you call the LoadScene method?
Answer by mbro514 · Jul 05, 2020 at 07:58 PM
This should solve your problem. Unity Answers Page
I also have a suggestion that is completely unrelated to your problem. Instead of using the switch statement in your second script, you could just write:
public void selectScene()
{
SceneManager.LoadScene(this.gameObject.name);
}