Don’t put off loading scenes until later if you can load them asynchronously now

I used to struggle to find clean ways to load unity scenes.

Then I stopped struggling and started using the snippet bellow while I wait for a cleaner approach.

using System;
using UnityEngine;
using System.Collections;
using UnityEngine.Assertions;
using UnityEngine.SceneManagement;
 
public class AsyncSceneLoader
{
    readonly string sceneName;
    public AsyncOperation async;
 
    public AsyncSceneLoader( string sceneName )
    {
        this.sceneName = sceneName;
    }
 
    public void Load()
    {
        Assert.IsFalse( string.IsNullOrEmpty( sceneName ) );
        AsyncSceneLoaderWizard.Instance.StartCoroutine( Load( sceneName ) );
    }
 
    IEnumerator Load( string sceneName )
    {
        if ( string.IsNullOrEmpty( sceneName ) )
        {
            throw new Exception( "Can't load empty string as scene name" );
        }
 
        async = SceneManager.LoadSceneAsync( sceneName );
        async.allowSceneActivation = false;
        yield return async;
    }
 
    public void Activate()
    {
        async.allowSceneActivation = true;
    }
}
 
public class AsyncSceneLoaderWizard : GameObjectSingleton<AsyncSceneLoaderWizard>
{
    public static AsyncSceneLoader SettingsSceneLoader = new AsyncSceneLoader( "Settings Scene" );
 
    public static AsyncSceneLoader EndgameCreditsSceneLoader = new AsyncSceneLoader( "Endgame Credits" );
 
    public void Start()
    {
        SettingsSceneLoader.Load();
        EndgameCreditsSceneLoader.Load();
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *