Search Unity

Feedback The most optimal way to load a new scene

Discussion in 'Scripting' started by ChunkyUS, Jan 18, 2023.

  1. ChunkyUS

    ChunkyUS

    Joined:
    Nov 23, 2022
    Posts:
    1
    Hi all,

    First post here so forgive me for any mistakes I may make. I am making an extremely basic 2D platformer as my first game to learn to get comfortable with the basics around Unity. I have an ending point of every level where, once the player reaches the end, it loads the next level. The levels will progress in the order they are listed in my Build Settings. I currently have this GameManager script that controls the level progression.

    Code (CSharp):
    1. public class GameManager : MonoBehaviour
    2. {
    3.  
    4.     public GameObject Player;
    5.  
    6.     Scene currentScene;
    7.  
    8.     // Start is called before the first frame update
    9.     void Start()
    10.     {
    11.         Application.targetFrameRate = 60;
    12.  
    13.         currentScene = SceneManager.GetActiveScene();
    14.     }
    15.  
    16.     // Update is called once per frame
    17.     void Update()
    18.     {
    19.         if(Input.GetKeyDown(KeyCode.R))
    20.         {
    21.             RestartLevel();
    22.         }
    23.     }
    24.  
    25.     public void RestartLevel()
    26.     {
    27.         Scene scene = SceneManager.GetActiveScene();
    28.         SceneManager.LoadScene(scene.buildIndex);
    29.         Debug.Log(scene.name + " loaded");
    30.     }
    31.  
    32.     public void LoadNextLevel()
    33.     {
    34.         SceneManager.LoadScene(currentScene.buildIndex + 1);
    35.     }
    36. }
    I listen for user input and restart the level when the R key is pressed.

    I have a script attached to my Player that contains the following:
    Code (CSharp):
    1. private void OnTriggerEnter2D(Collider2D other)
    2.     {
    3.         if (other.transform.tag == "Level_End")
    4.         {
    5.             gameManager.LoadNextLevel();
    6.         }
    7.     }
    My logic is that when the player enters the trigger for the end of the level, it triggers the game manager to load the next level in the build index. So far it has worked exactly how I want it to.

    My question is, is there anything wrong with what I am doing here? Is the code I implemented unsafe or not optimal in any way?

    The one thing I can think of that I know I need to implement is to check if it is the final level of the game and be sure to not try and load the next scene in the build index, since it will not exist.

    Any constructive criticism would be greatly appreciated! Thanks!