Async code on scene change

What happens to async code on a scene change?

Found the answer – TL;DR HORRIBLE, HORRIBLE THINGS HAPPEN


(I reported the bug after being able to reproduce it every time)

What happened
If you change scenes while async tasks are still going, it will bug the hell out of the next scene. I had 2 completely irrelevant scripts that would awake() twice, sometimes even times.

They were confirmed multiple instances of these 2 scripts (lobbyUI and lobbyPhoton), including the parent gameObj’s (LobbyUI and LobbyMgr). I would even trace where they are in the hierarchy and it’d always say top level at /LobbyMgr and /LobbyUI, where I would always see only ONE.

Not only that, ALL USES were singletons so the situation is impossible unles I dropped it in 2 gameObj’s by accident, but I’d “find all references within scene” and nope – just the 1’s.

On Awake() if I tested for null for the singleton, it would SKIP the logic (it was clearly NOT null) and make a singleton of itself, anyway.

This is a HORRIBLE HORRIBLE bug that took me days to debug.

RESOLVED by waiting for 0.1 second before swapping scenes. Literally this was the solution. I found out there were some unfinished async tasks. Surely the non-lazy resolution would be to check all of the callbacks to ensure they are all done.

Either way, Unity needs better garbage collection when changing scenes for async tasks that are incomplete.