I have created two scenes so far: one title screen and one level. I would like to know how I can build an object so that when I give the command to load the other scene, it does so. I have currently imported the scenemanager and tried using the LoadScene command, but it does nothing for both scenes. I have heard you can create a GameObject to bridge between scenes, but I am not sure where to put it and how to implement it?
You could create a singleton-style “LevelManager” component that handles scene changes. This object would start in your first scene, and then it would persist throughout the game by using the DontDestroyOnLoad method.
For example:
using UnityEngine;
using UnityEngine.SceneManagement;
public class LevelManager : MonoBehaviour
{
private static LevelManager _instance;
public static LevelManager Instance
{
get
{
if(_instance == null)
{
_instance = FindObjectOfType<LevelManager>();
}
return _instance;
}
private set
{
_instance = value;
}
}
public UnityEvent OnSceneLoaded;
public Scene CurrentScene { get; private set; }
private void Awake()
{
// enforce "there can only be one" rule of Singleton pattern
if(Instance == null)
{
Instance = this;
DontDestroyOnLoad(gameObject);
}
else if(Instance != this)
{
Destroy(gameObject); // if one already exists, destroy this one
}
}
private void OnEnable()
{
SceneManager.sceneLoaded += this.onSceneLoaded;
}
private void OnDisable()
{
SceneManager.sceneLoaded -= this.onSceneLoaded;
}
private void onSceneLoaded(Scene scene, LoadSceneMode mode)
{
CurrentScene = scene;
OnSceneLoaded.Invoke();
}
public void LoadScene(string levelName)
{
SceneManager.LoadScene(levelName);
}
public void LoadScene(string levelName, LoadSceneMode mode)
{
SceneManager.LoadScene(levelName, mode);
}
public void LoadScene(int levelIndex)
{
SceneManager.LoadScene(levelIndex);
}
public void LoadScene(int levelIndex, LoadSceneMode mode)
{
SceneManager.LoadScene(levelIndex, mode);
}
}
With that in your game, from any script you can call LevelManager.Instance.LoadScene(“MainMenu”) and the game will change to that scene, and this LevelManager will still be there on the other side.
If you have any questions about that code, feel free to ask.
Thanks, but I just figured out my problem was I never built the project. The help is still nice tho.
1 Like