I am writing a Unity library to load game worlds over the internet. It uses coroutines (and thus needs to extend MonoBehaviour and attach to a GameObject in the scene), and it also needs to be able to keep working during scene changes (I need to start downloading a world in one scene, then load another scene and begin generating the world).
Currently works like this:
(1) Code instructs singleton World Loader library to initialize.
(2) Library creates a GameObject, marks it as DontDestroyOnLoad, attaches itself to it (so it can use coroutines), and points a static reference to the instance of itself it created.
(3) Code calls load coroutine in Loader library.
(4) Code waits a bit, then switches to a new Unity scene.
(5) From what I can tell, switching scenes causes the coroutine to instantly and silently die in the middle of it’s work.
I am assuming that even though the Library’s GameObject is marked as DontDestroyOnLoad, the script attached to it is being reloaded on scene change (And indeed, it’s OnDisable and OnEnable functions are being called). I don’t know why this would happen.
Questions:
(1) Are coroutines supposed to die on scene changes, or am I doing something wrong?
(2) I could add some OnEnable logic to detect when the script had been reloaded, and fire up the coroutine again (which would involve more logic to figure out what step it was at when it died), but it would be terribly inelegant and a potential source of future bugs. Should I go this route, or would it make more sense to pursue some form of system level threading rather than trying to work with Unity’s coroutines? (Is there a solution which would make more sense?)