Loop Fail. Feel free to ROAST me

So clearly theres something im just not seeing or missed so feel free to roast me because i cant see the mistake i made yet.

And then i run the Game.

Hi Jayy,

I’m not sure what your question is, as you’ve not actually asked one :slight_smile:

Your error message however indicates that you’ve not added a scene to your Build Settings, assuming you have another scene to add. Looking at the code it looks like you are trying to go back to the first level when you complete the last level, this is only a guess.

I would start by adding some Debug.Log statements, before the if to output what the variable currentSceneIndex is, and also the value of the sceneCountInBuildSettings property. From this output you may be able to ascertain why your if statement is not running as expected.

Remember, arrays are zero-based, so the first scene in your Build Settings is index zero, the count you return of how many scenes there are however will not be zero-based, so if you have 5 scenes, you’ll return the value of 5. Big clue here :slight_smile:

On a related note, you could re-use the method you have above LoadNextScene, named RestartFirstLevel instead of setting nextSceneIndex = 0 etc.

Please note, it’s better to copy/paste your code and apply the code fencing characters, rather than using screenshots. Screenshots are ideal for displaying specific details from within a game engine editor or even error messages, but for code, they tend to be less readable, especially on mobile devices which can require extensive zooming and scrolling.

You also prevent those that may offer to help you the ability to copy/paste part of your code back to you with suggestions and/or corrections, meaning that they would need to type a potentially lengthy response. You will often find that people are more likely to respond to your questions if you make it as easy as possible for them to do so.

Hope this helps :slight_smile:


See also;

Just finished Fixing my game and im gonna try this.

1 Like

Great, if it resolves the problem please mark the topic as solved Jayy :slight_smile:


See also;

Alright so i tried a few things. I made sure all my Build settings was correct and i checked in the console if it was correct aswel an printed what scene i was on.

this is my code same as up top the only difference was that i did what you said and used my RestartFirstLevel to loop back to the first scene.

private void ReturnFirstLevel()
{
SceneManager.LoadScene(0);
}

private  void LoadNextScene()
{
    int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
    int nextSceneIndex = currentSceneIndex + 1;
    print(currentSceneIndex);
    if(currentSceneIndex == SceneManager.sceneCountInBuildSettings)
    {
        ReturnFirstLevel(); // loop back
    }
    SceneManager.LoadScene(nextSceneIndex);
}

So I gave you a clue in my previous response regarding the array of scenes in the build being zero-based…

Yeah. the only thing i can get out of it is that it counts it as 1 instead of zero and ive tried things like
if the current scene is 5 go back to 1 or 0 but either it doesnt work or im coding it incorrectly.

The issue is with your if statement.

Consider how many scenes you have in your build, based on the above screenshot it is 6.

Now consider what the scene index will be on when you are on that last scene, it will be 5, because the array is zero-based.

At the moment your if statement would be saying “is 5 equal to 6”,this will always return false so the logic continues to call your LoadNextScene method, but because there are noore scenes to load, your +1 on the current scene index causes the error message you are receiving because you are trying to access am array element that doesn’t exist.

The solution will be to reduce your total count of scenes by 1 to reflect the zero-based array;

if(currentSceneIndex == SceneManager.sceneCountInBuildSettings - 1)

Hope this helps :slight_smile:

Wooooow. I feel dumb. I knew i had to make it 5 but i didn’t know you could just subtract like that and it makes perfect sense. I wonder why it worked for Ben when he was demonstrating in the video but this was really helpful overall. There’s someone else that had this same exact problem so ill make sure to show them this thread. I appreciate you challenging me to figure it out. Big thanks.

1 Like

Hi Jayy,

You’re more than welcome.

Debugging is a skill in its own right, it’s one worth practising as frequently as you can as the more you do it the more often you’ll spot issues early on.

In this particular case a Debug.Log statement before the if outputting both the current scene index and the total number of scenes would have probably led you to the right place.

It is also worth checking with the Unity documentation regarding the types, methods and properties, doing so in this case would have told you that sceneCountInBuildSettings returns and int, knowing this would have proba ly led you to trying to subtract from it, or, perhaps via an intermediate variable.

Absolutely no reason to feel silly, it’s a learning journey, no one was just an expert, everyone starts as a beginner and progresses, you yourself will already know much more about Unity and C# than other people. Keep building on the knowledge and skills. :slight_smile:

1 Like

In less than 10 minutes i just did. Thanks to your help i was able to figure out how to make my levels where instead of dying and going back to the very first level you go back one level and if you are on the first level you will just loop back to the first level again.

I did this.

private void ReturnFirstLevel()
    {
        int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;

        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex - 1);
        if (currentSceneIndex == SceneManager.sceneCountInBuildSettings - 6)
        {
            SceneManager.LoadScene(0);
        }
    }
1 Like

Well done for extending the functionality and doing something on your own with this.

Couple of suggestions for going forward, and this is slightly outside the scope of this specific topic, however;

  • be wary of adding specific values like that, e.g. the 6, in the course they are referred to as magic numbers. The reason these can be a problem is at some point if you add another level, you have to remember to change that 6 to a 7, you probably won’t remember to do this, and then wonder why you get errors, or, never get to your last level :slight_smile:

  • be aware of the method names and what they do, in the above, ReturnFirstLevel should do exactly that, return to the first level. Rather than having lots of code in one method, muddying the waters a little, you could consider having LoadFirstLevel and LoadCurrentLevel. LoadFirstLevel is always just going to load the very first scene (I am assuming at this point there is no Start scene / Menu scene etc). LoadCurrentScene (or perhaps LoadPreviousScene in your mechanic here) would do exactly that.

    Much like debugging, refactoring your code is another skill that comes with time, but you will start to spot when it is probably time to start breaking things into smaller pieces when a method gets a bit code heavy.

Also, try to spot any duplicates in your code and try to reduce, as an example based on your above snippet;

This gets the current scene index;

int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;

This loads a scene, getting the current scene index (again) and deducting 1 from it;

SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex - 1);

You could just have this;

int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;

SceneManager.LoadScene(currentSceneIndex - 1);

It may seem fairly trivial but GetActiveScene does exactly that, it loads an entire scene, with references to every object in that scene. By removing this duplication, you get a little performance boost :slight_smile:

Hope this helps :slight_smile:

Yeah i could definitely see me screwing up because of that if i decide to make more levels and in general thanks.

1 Like

You also have a bit of overlapping code, e.g in the statements, you first say “go load this level” and then on the next statement you say, if its scene index zero, load the first scene. It may be more by luck at the moment that the behaviour you are experiencing is working :slight_smile:

instead of - 6 now i did sceneCountinBuildsettings - sceneCountinBuildsettings.

1 Like

If I were to refactor the above, I’d probably have something like this, see if this makes sense to you;

private int currentSceneIndex = -1;

private void Start()
{
	currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
}

private void Reload()
{
	if(currentSceneIndex == 0)
	{
		LoadFirstScene();
	}
	else
	{
		LoadPreviousScene();
	}
}

private void LoadFirstScene()
{
    SceneManager.LoadScene(0);
}

private void LoadPreviousScene()
{
    SceneManager.LoadScene(currentSceneIndex - 1);
}

The above declares a member variable to store the current scene index of the level. This relies on the GameObject that has this script attached to be in each scene.

The Start method sets the member variable, once, setting it to the value of the loaded scene.

The Reload method (you could probably rename to something more suitable) determines whether the very first scene should be loaded, or, the previous one. Either case has a specific method which is called.

Both methods are then very specific about what they do, easily readable, require no comments and have no magic numbers etc.

The member variable is at the class level, so it is available to all methods within that class. In case you are wondering, I have declared it and initialised it with a -1 at the beginning to prevent any actual scenes being loaded inadvertently, an int defaults to a value of zero. By setting it to -1, if it was used without being set to a proper scene index, an error would be thrown.

Note, depending where this code actually live in your project, you may need to make the Reload method public so that it can be accessed by other classes. I’m guessing this is from some kind of SceneLoader.cs or LevelLoader.cs?

oh yeah that’s way easier to read. ill make sure to try this.

You’re idea of doing this by the way;

sceneCountinBuildsettings - sceneCountinBuildsettings

definitely heading/thinking in the right direction, if you consider what this would actual end up as though, the result would also be zero - hence the simplification in the if statement above to just check for zero. :slight_smile:

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms