I created a script that changes the transparency of the GameObject it's attached to and I do the transparency change in a fading coroutine which needs to be cancellable (and canceled everytime we call ChangeTransparency() with a new value). I managed to get it working the way I want it but I want to handle the OperationCanceledException that is flooding my Console. I know that you cannot wrap a yield return statement inside a try-catch block.
What is a proper way to handle Exceptions inside Unity coroutines?
Here is my script:
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);
}
}
}
My temporary solution was to check for the token's cancellation flag and break out of the while loop. While it solved this current problem, I am still in need of a way to handle these exceptions that are thrown in asynchronous methods (coroutines) in Unity.