Async code on scene change
What happens to async code on a scene change?
Answer by MrLucid72 · Mar 13, 2017 at 02:21 PM
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.
See attached screenshot
Relevant post @ http://answers.unity3d.com/questions/1325200/startawake-being-called-twice-after-already-checki.html
Your answer
![](https://koobas.hobune.stream/wayback/20220612113057im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Async Level loading issue. 0 Answers
Load level async 0 Answers
change scene in network lobby manager 1 Answer
Load level async 1 Answer
How do I preload multiple scenes? 0 Answers