I have a component that is in charge of generating a level at runtime, and this is an operation that takes quite some time. As a consequence, I experience a hang when this operation is executed (when the scene is loaded).
This problem can be summarized to the fact that SceneManager.LoadSceneAsync in fact is not async at all in its second phase, when it initializes all the objects.
There are three approaches I have searched for and thought about:
Slicing the operation as explained on this video:
This is non-trivial, I would have to rewrite chunks of code for the sake of avoiding a few seconds hiccup at scene load. Furthermore, the person explaining in the video says that they changed Unity source code which I don't have access to.
Running the operation in a background thread:
This is definitely interesting, it would require minimal changes. The only problem is that at some point I have to create Unity objects (GameObject
, Mesh
etc) and this is not possible when outside Unity thread.
I was thinking more or less of this code to be run on the background thread:
class Builder
{
public void Build()
{
// 1. do something long
// 2. create Unity object with result from #1
// something like that
// await RunInUnitySynchronizationContext(() => new GameObject(...))
// 3. do extra stuff on the result of #2
}
}
The thing is I have no idea at all on how that second step should be written, if possible at all.
Use a non-animated Loading screen and wait for it to finish:
This is the simplest and effectively does away with the problem by 'just' hiding it.
Question:
What's an effective approach to solve this problem?