Skip to content

Scene Initialization using UniSwitcher

C. Plug edited this page Apr 25, 2023 · 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 method is async because it withholds the transition while the initialization code runs!

⚠️ Warning
In other words, if you have an entry point in the scene you transitioned to, the user will not see the scene below until this method finishes running!!

If your initialization code does not contain any asynchronous methods, you may receive a warning to remove async. However, you must not remove async from the Fire() method as it is mandatory (you will have to handle return values, which you probably don't want to).
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);
}

⚠️ Warning
Placing no-op async code before your entry point code might lead to weird behavior. (fact check required here)

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 under discussion.)

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 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