【发布时间】:2022-01-18 04:03:25
【问题描述】:
我创建了一个脚本来更改它所附加的 GameObject 的透明度,并且我在需要取消的褪色协程中进行透明度更改(并且每次我们使用新值调用 ChangeTransparency() 时都会取消)。我设法让它按照我想要的方式工作,但我想处理充斥我控制台的OperationCanceledException。我知道您不能将 yield return 语句包装在 try-catch 块内。
在 Unity 协程中处理异常的正确方法是什么?
这是我的脚本:
using System;
using System.Collections;
using System.Threading;
using UnityEngine;
public class Seethrough : MonoBehaviour
{
private bool isTransparent = false;
private Renderer componentRenderer;
private CancellationTokenSource cts;
private const string materialTransparencyProperty = "_Fade";
private void Start()
{
cts = new CancellationTokenSource();
componentRenderer = GetComponent<Renderer>();
}
public void ChangeTransparency(bool transparent)
{
//Avoid to set the same transparency twice
if (this.isTransparent == transparent) return;
//Set the new configuration
this.isTransparent = transparent;
cts?.Cancel();
cts = new CancellationTokenSource();
if (transparent)
{
StartCoroutine(FadeTransparency(0.4f, 0.6f, cts.Token));
}
else
{
StartCoroutine(FadeTransparency(1f, 0.5f, cts.Token));
}
}
private IEnumerator FadeTransparency(float targetValue, float duration, CancellationToken token)
{
Material[] materials = componentRenderer.materials;
foreach (Material material in materials)
{
float startValue = material.GetFloat(materialTransparencyProperty);
float time = 0;
while (time < duration)
{
token.ThrowIfCancellationRequested(); // I would like to handle this exception somehow while still canceling the coroutine
material.SetFloat(materialTransparencyProperty, Mathf.Lerp(startValue, targetValue, time / duration));
time += Time.deltaTime;
yield return null;
}
material.SetFloat(materialTransparencyProperty, targetValue);
}
}
}
我的临时解决方案是检查令牌的取消标志并跳出 while 循环。虽然它解决了当前的问题,但我仍然需要一种方法来处理这些在 Unity 中的异步方法(协程)中引发的异常。
【问题讨论】:
-
为什么不在新的
ChangeTransparency调用中停止之前的协程? -
当您将
token.ThrowIfCancellationRequest()替换为if (token.IsCancellationRequested){ yield break; }时,您看到了什么异常?你得到了什么“异步异常”? -
我编辑了我的最后一句话。我指的是异步运行的方法(协程)中抛出的异常。检查令牌的取消标志时,我没有收到任何异常,但我仍然希望能够处理异常。
标签: c# unity3d coroutine cancellation