Reputation: 886
Reference: How to execute async task in Unity3D?
I have a script dynamically loading high LOD models on a button click. Unfortunately Unity will lag, or drop frames. In reality I'm not sure which, but it appears to be frozen until the large model is loaded. This isn't very user friendly. In an ideal world, I am able to display a 'Loading...' text message to the user while a model is loading.
From what I found, async methods are the best way to accomplish this, but I can't seem to implement an async method. I read elsewhere that coroutines are the clean way to execute asynchronous tasks. I tried...
IEnumerator txtTask()
{
yield return new WaitForSeconds(0);
LoadingTxt.GetComponent<UnityEngine.UI.Text>().enabled = true;
}
And then calling this coroutine at the start of the model load function,
StartCoroutine(txtTask());
But this doesn't work, Unity still temporarily hangs. The model will load and so will the text at the same time.
Upvotes: 0
Views: 2438
Reputation: 127573
Coroutines still only use a single thread to process so when you yielded in your method all you did was make the text wait for 0 seconds to show up but it still used the UI thread (which is being locked up by your loading code) to display it.
What you need to do is delay the loading code for one frame so the UI can update then let the slow operation run.
private UnityEngine.UI.Text textComponent;
void Start()
{
//You should do your GetCompoent calls once in Start() and keep the references.
textComponent = LoadingTxt.GetComponent<UnityEngine.UI.Text>()
}
IEnumerator LoadData()
{
textComponent.enabled = true; //Show the text
yield return 0; //yielding 0 causes it to wait for 1 frame. This lets the text get drawn.
ModelLoadFunc(); //Function that loads the models, hang happens here
textComponent.enabled = false; //Hide the text
}
You then call StartCoroutine(LoadData());
to start the corutine off in your button code.
Upvotes: 1