Skip to content

Scene Initialization using UniSwitcher

Collapsed Plug edited this page May 26, 2022 · 3 revisions

You can run an initialization code for the scene using UniSwitcher.

ISceneEntryPoint interface

UniSwitcher will look for an implementation of the ISceneEntryPoint interface in the Scene.

This interface requires you to implement the following methods.

UniTask Fire()

This is the method that is run on the scene change.

public async UniTask Fire() {
    await InitializeTheScene();
}

You may have noticed that this is an async method. This implementation is to hold the transition while the initialization code runs.
In other words, if you enable transitions, the user will not see the scene below until this method finishes running.

If your initialization code does not have to be asynchronous, you may receive a warning to remove async. You must not remove async from the Fire() method as it is mandatory.
To avoid this warning, you do not have to make it async forcibly; instead, add UniTask no-op code such as await UniTask.Yield(); or await UniTask.Delay(TimeSpan.Zero) after your initialization code.

public async UniTask Fire() {
    InitializeTheScene(); // Not Async
    await UniTask.Delay(TimeSpan.Zero);
}

Exception Handling

Any unhandled exception can be caught in the OnFailure(Exception) method of the same interface, explained later.

bool Validate()

This method is mainly meant for development purposes. Return true if the data look valid.

If you return false, it will throw an unhandled ArgumentException,
which means the game may lock up!

(The ability to allow the code to catch this exception is discussed.)

void OnFailure(Exception e)

Any exceptions thrown in the Fire() method will result in this method being called.

This method is a fail-safe method for the cases where your initialization code crashes.
This method should inform the player of the error and enable them to carry on by, e.g., going back to the previous Scene.

Clone this wiki locally