unity中 IEnumerator Type(string filePath) { Debug.Log($"正在加载原生文件:{filePath}"); string targetText; //加载原生文件 RawFileOperationHandle handle4 = package.LoadRawFileAsync(filePath); yield return handle4; if (handle4.Status == EOperationStatus.Failed) { Debug.Log($"正在加载原生文件错误 "); } // byte[] fileData = handle.GetRawFileData(); targetText = handle4.GetRawFileText(); Debug.Log("正在加载原生文件 2: " + targetText); index = 0; currentText = ""; while (index < targetText.Length) { Debug.Log($"正在打印:{targetText[index]}"); currentText += targetText[index]; // 将当前字符添加到当前文本 textComponent.text = currentText; // 更新Text组件的文本 index++; // 将聊天文本的位置设置到最底部 Canvas.ForceUpdateCanvases(); my_ScrollRect.verticalNormalizedPosition = 0; yield return new WaitForSeconds(typingSpeed); // 等待一定时间 } }这段代码使用unitask方式帮我写一遍
时间: 2024-03-17 09:40:48 浏览: 14
当然,下面是使用UniTask重写后的代码:
```csharp
private async UniTaskVoid Type(string filePath)
{
Debug.Log($"正在加载原生文件:{filePath}");
string targetText;
//加载原生文件
RawFileOperationHandle handle4 = package.LoadRawFileAsync(filePath);
await handle4;
if (handle4.Status == EOperationStatus.Failed)
{
Debug.Log($"正在加载原生文件错误 ");
return;
}
// byte[] fileData = handle.GetRawFileData();
targetText = handle4.GetRawFileText();
Debug.Log("正在加载原生文件 2: " + targetText);
index = 0;
currentText = "";
while (index < targetText.Length)
{
Debug.Log($"正在打印:{targetText[index]}");
currentText += targetText[index]; // 将当前字符添加到当前文本
textComponent.text = currentText; // 更新Text组件的文本
index++;
// 将聊天文本的位置设置到最底部
Canvas.ForceUpdateCanvases();
my_ScrollRect.verticalNormalizedPosition = 0;
await UniTask.Delay(TimeSpan.FromSeconds(typingSpeed)); // 等待一定时间
}
}
```
在上面的代码中,我们使用了UniTask的异步方法来代替原来的协程,其中包括使用UniTask的`UniTask.Delay()`方法来替换原来的`yield return new WaitForSeconds()`方法来实现等待一定时间的功能。同时,使用UniTask的`UniTaskVoid`来替代原来的`IEnumerator`类型,使得代码更加简洁易懂。