Scene Loading
Basic
Tested this in a new project. The idea is to start scene preloading when Return
button is pressed and save AsyncOperation
that is doing it, disallow scene activation for it and allow it when you need the scene to be loaded as soon as it's ready.
I would expect it to be loaded into memory, be careful if you are RAM-bounded because both scenes will take up memory space until one is unloaded.
Reproduce:
- Create a new project.
- Create 2 scenes:
- Add both scenes to
Build Settings
.
- Open "menu" scene.
- Create
GameObject
and add PreloadSceneInUnity
component to it.
- Enter playmode.
- Press
Return
and see "maingame (is loading)" in Hierarchy window.
- Press
Space
- "maingame" scene will open.
Code
Git: Preload scene in unity
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PreloadSceneInUnity : MonoBehaviour
{
[SerializeField] private string _sceneName = "maingame";
public string _SceneName => this._sceneName;
private AsyncOperation _asyncOperation;
private IEnumerator LoadSceneAsyncProcess(string sceneName)
{
// Begin to load the Scene you have specified.
this._asyncOperation = SceneManager.LoadSceneAsync(sceneName);
// Don't let the Scene activate until you allow it to.
this._asyncOperation.allowSceneActivation = false;
while (!this._asyncOperation.isDone)
{
Debug.Log($"[scene]:{sceneName} [load progress]: {this._asyncOperation.progress}");
yield return null;
}
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Return) && this._asyncOperation == null)
{
Debug.Log("Started Scene Preloading");
// Start scene preloading.
this.StartCoroutine(this.LoadSceneAsyncProcess(sceneName: this._sceneName));
}
// Press the space key to activate the Scene.
if (Input.GetKeyDown(KeyCode.Space) && this._asyncOperation != null)
{
Debug.Log("Allowed Scene Activation");
this._asyncOperation.allowSceneActivation = true;
}
}
}
Advanced
If you are not satisfied with how scene loading works in UnityEngine.SceneManagement
- I suggest you take a look at Addressables
package that Unity provides, it has support for scene loading as well, but be aware that it's a lot more complicated to get into and there is a learning curve that requires to learn quite a few more things before scene loading.
AsyncOperation
or other non-blocking operations. However, one can find several different solutions when using these. \$\endgroup\$