unity async and/or协程实现?

Unity async and/or coroutine implementation?

参考:How to execute async task in Unity3D?

我有一个脚本,可以在单击按钮时动态加载高 LOD 模型。不幸的是,Unity 会滞后或丢帧。实际上我不确定是哪一个,但在加载大型模型之前它似乎被冻结了。这不是很用户友好。在理想情况下,我可以在加载模型时向用户显示 'Loading...' 文本消息。

根据我的发现,异步方法是实现此目的的最佳方式,但我似乎无法实现异步方法。我在别处读到协程是执行异步任务的干净方式。我试过了...

IEnumerator txtTask()
{
    yield return new WaitForSeconds(0);
    LoadingTxt.GetComponent<UnityEngine.UI.Text>().enabled = true;
}

然后在模型加载函数的开始调用这个协程,

StartCoroutine(txtTask());

但是这样不行,Unity还是暂时挂了。将同时加载模型和文本。

协程仍然只使用一个线程来处理,所以当你在你的方法中让步时,你所做的只是让文本等待 0 秒显示,但它仍然使用 UI 线程(正在被您的加载代码锁定)以显示它。

您需要做的是延迟一帧的加载代码,以便 UI 可以更新然后让缓慢的操作 运行。

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
}

然后调用 StartCoroutine(LoadData()); 以在按钮代码中启动协程。