Game has a Main scene and a Map scene. I load Map scene additively to the Main one.
Counterintuitively, but by Unity design, Awake() on Map scene scripts gets called before I can set Map scene as Active (via SceneManager.SetActiveScene()).
Thus, all scripts that instantiate something, end up instantiating their stuff on Menu scene. Result: errors when Map scene eventually gets unloaded - because parts of its stuff got stuck on Main scene.
For test purposes, the loading function looks like this:
IEnumerator LoadingCoroutine ()
{
var asyncOp = SceneManager.LoadSceneAsync ("Map", LoadSceneMode.Additive);
asyncOp.allowSceneActivation = true;
while (!asyncOp.isDone)
{
yield return null;
}
SceneManager.SetActiveScene (SceneManager.GetSceneByName ("Map"));
sceneActivated?.Invoke (); //Note that for later
}
Tried a SceneManager.sceneLoaded delegate, like this:
using UnityEngine.SceneManagement;
public class TEST_OnSceneLoaded : TEST_OnAwake
{
protected override void Awake ()
{
SceneManager.sceneLoaded += SceneLoaded;
}
void SceneLoaded (Scene scene, LoadSceneMode mode)
{
SceneManager.sceneLoaded -= SceneLoaded;
MakeTestObject ("OnSceneLoadedObject");
}
}
No luck - SceneLoaded gets called before Scene activation, resulting in the aforemented problem with misplaced objects.
Tried a custom solution - remember a call to a custom âsceneActivatedâ delegate in loading coroutine?
public class TEST_OnSceneActivated : TEST_OnAwake
{
TEST_SceneActivation scenActivation;
protected override void Awake ()
{
scenActivation = FindObjectOfType<TEST_SceneActivation> ();
scenActivation.sceneActivated += SceneLoaded;
}
void SceneLoaded ()
{
scenActivation.sceneActivated -= SceneLoaded;
MakeTestObject ("OnSceneActivatedObject");
}
}
This works as intended. Object is created on the Map scene.
Now I gotta check and rewrite several hundred scripts (the joys of a complex first game, ahh), but thatâs not what bothers me.
What bothers is: is this completely custom solution a correct one? I feel like Iâm missing something obvious here. Isnât there some kind of simple, built-in solution? I mean, the cases where stuff wants to be instantiated on Awake() + project relies on additive scene loading must be pretty common - do they all have to do weird flexes like that?