I have a scene with lots of lightweight objects and one that takes anywhere between 10 and 45 seconds to load.
At a high level, the Awake method does...
- Query database
- For each result do some (fairly heavy) calculations
- Populate a list
- Use that list to generate game objects
[Only the last step of which requires the main thread]
I have another scene to display a loading screen. It has a UI panel with a shader that shows an animation.
The Loading screen starts a coroutine to switch level...
private IEnumerator LoadNewScene() {
AsyncOperation async = SceneManager.LoadSceneAsync("GalaxyMap", LoadSceneMode.Single);
while (!async.isDone) {
yield return null;
}
}
At which point, the animation freezes for 10-45 seconds while the heavy object loads.
In an attempt to make the animation CPU-independent, it's coded as a shader using the built-in _Time
property.
I assume this is because my heavy object's Awake()
is running on Unity's main thread and thus is blocking updates to the shader.
If so, I can move a lot of the heavy lifting onto a background thread, but I can't work out how to release the thread back to Unity temporarily.
The Awake() method isn't async
, and any attempt to create a Task and wait for it will just block the same thread.
Conversely, I could have a completion callback for when the load is done. That would allow me to release the main thread sooner, however, Unity would think my scene had finished loading prematurely and remove the loading screen.
How can I either:
- Release control of the thrad intermittently so Unity can refresh the UI
- Explicitly tell Unity when it should consider a scene "loaded" and ready for display
?
await
was re: the C# job system). I've identified work that can run on another thread (and I can handle dispatching/invoking to get the UI thread to do something afterwards). Where I'm struggling is to get Unity to think "Level still loading" until that process completes if it's not on the main thread (egSceneManager.LoadSceneAsync
won't wait for a Coroutine) \$\endgroup\$