Ok, I think I see what you are aiming to do, and yes I believe you could get the desired outcome the way you are suggesting.
You are really just asking whether the current scene is the last playable level or not, if it is, start again, if its not, load the next playable scene.
I’m guessing your LevelManager isn’t actually included in each scene? You would only want to perform that foreach iteration the once for the life time of the game, effectively extracting the scene/indexes from the build settings. There is still a manual step there which is putting the scenes into the build settings and of course it will rely heavily on the naming of your levels, misspell one and that level won’t be included.
So, you end up with a list of scene index numbers, which, depending on where you have put the non-playable scenes in the build settings may look like this;
0,1,2,3,4,5,9,10 - where 6,7,8 were non-playable scenes
Based on what you have in the pseudo code example, nextIndex would get incremented after scene index 5, it wouldn’t equal the last playable scene index (10) and would then try to load scene index 6 - a non-playable scene.
Unless I’ve misunderstood?
If you had this;
Build Settings;
Lose 0
Menu 1
Settings 2
Dev Settings 3
Level01 4
Level02 5
Level03 6
You would only need to know about the total number of scenes, and which index the first playable scene was, after that you can just increment numbers whilst the number is <= the total. As soon as the next number is higher than the total, go back to the first playable-scene.
Assuming the LevelManager is only loaded once itself you could have something like this;
// private fields to retain some useful settings/info
private int _totalScenes = SceneManager.sceneCountInBuildSettings;
private int _nonPlayableScenes = 4;
private int _firstPlayableSceneIndex = (totalScenes - nonPlayableScenes) + 1;
private int _activeSceneIndex;
// loads the next appropriate scene based on the current scene index
LoadNextScene()
{
_activeSceneIndex = SceneManager.GetActiveScene().buildIndex;
if ( (_activeSceneIndex +1) < _totalScenes)
{
// load the next playable level
SceneManager.LoadScene(_activeSceneIndex +1);
}
else
{
// load the first playable level
SceneManager.LoadScene(firstPlayableSceneIndex)
}
}
Note: If there are additional load a level methods, you would want to ensure that the _activeSceneIndex was being set accordingly (refactor to another method and call it from each of the load methods etc)
The only downside I can see with the above is that it assumes that the next level is always playable, thus, you need to ensure that non-playable scenes are first in the build settings and, you set _nonPlayableScenes accordingly.