Random issues with level transitions

I made a platform game with 8 levels and a main menu that can be accessed from each level. Unfortunately, I encounter a problem that seems to be randomly generated - sometimes it appears, other times it doesn’t. Sometimes the problem is between levels 1 and 3, other times 7 and 8 and so on. Sometimes the problem is generated when I play levels one by one, other times when I enter a random level from the main menu. The problem is that after turning on the Level there is no background, and the character can only move sideways, without jumping. Often it is enough to enter another level from the menu or turn the game on and off for everything to work. The problem also appears when running the game as a file on another computer.

It is difficult for me to fix this error because of the randomness of this situation. I think that a good clue to the source of the problem is that I did not use tilemaps, I created subsequent levels by copying previous scenes.

I was thinking about using a Singleton or Service Locator for the level change structure, but I’m not sure if it’s a good idea.

My Exit script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class Exit : MonoBehaviour
{

  public int nextSceneLoad;
void OnTriggerEnter2D(Collider2D other)
{
   if(other.gameObject.tag == "Sev")
   {
        int currentSceneIndex = SceneManager.GetActiveScene().buildIndex; 
         SceneManager.LoadScene(currentSceneIndex +1);
    }
     if(nextSceneLoad > PlayerPrefs.GetInt("levelAt"))
        {
            PlayerPrefs.SetInt("levelAt",nextSceneLoad);
            
        }
   }

}

That’s why we invented debugging!

It won’t be useful or productive to think about random buzzwords you might have read on the internet if you haven’t actually found WHAT the problem is and are only referring to it as “The Problem.”

Sounds like you wrote a bug… and that means… time to start debugging!

By debugging you can find out exactly what your program is doing so you can fix it.

Use the above techniques to get the information you need in order to reason about what the problem is.

You can also use Debug.Log(...); statements to find out if any of your code is even running. Don’t assume it is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

I would also highly recommend not doing stuff like this:

… where you splatter string literals all over your code. Instead, try this pattern:

Here’s an example of simple persistent loading/saving values using PlayerPrefs:

Useful for a relatively small number of simple values.

1 Like

Thank you! I will try it :slight_smile: