- Home /
I made an levelcontroller in c# but it always goes back to level 2 does someone know how to fix this?
Everytime i start a level that is not level 1 i automatically go back to level 2 and when i start at level 2 i have to do it twice but i want players to choose wich level they want to start. here is the code: 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);
}
Answer by mbro514 · Jul 04, 2020 at 02:43 PM
I think that your problem is that you're setting the default value of _nextLevelIndex to 1, regardless of the scene you're starting in. Thus, when you finish the level, and _nextLevelIndex increases by 1 (giving it a value of 2), the scene "Level 2" is always loaded.
What I would do to fix this is make _nextLevelIndex a public variable or a private variable with [SerializeField] on top of it. Then, in the inspector in each scene, I would set _nextLevelIndex to the number of the level. That should solve your problem.
Answer by romeo160705 · Jul 04, 2020 at 02:56 PM
Thanks for the help man everything works fine now you saved me a lot of time
Your answer
Follow this Question
Related Questions
How to load a scene with GameFlow on button click ? ( XR RIG / Oculus Quest ) 0 Answers
Bolt Visual scripting and loading different scenes/levels 1 Answer
Classic Resident Evil-style room loading/level streaming? 4 Answers
Help with error message "Overwriting the same path as another open scene is not allowed" 0 Answers
Load Scene from .unity File 1 Answer