I’ve heard many good things about UniTask. The most common thing is that UniTask is faster than Coroutines. The other one is that UniTask is completely garbage-free (in some places they say there’s a bit, but anyhow less than coroutines).
I’m trying to learn how to use them, so my implementations might be off. However, in the below test, I’ve seen that UniTask is 2-3 times slower than Coroutines, and generates between 3 to 4 times more garbage than Coroutines:
public async void OnPointerDown(PointerEventData eventData)
{
StartCoroutine(ObjectRotateCoroutine());
await ObjectRotateUniTask();
}
private IEnumerator ObjectRotateCoroutine()
{
var end = Time.time + _duration;
while (Time.time < end)
{
_transform.Rotate(new Vector3(1, 1) * Time.deltaTime * 60);
yield return null;
}
}
private async UniTask ObjectRotateUniTask()
{
var end = Time.time + _duration;
while (Time.time < end)
{
_transform.Rotate(new Vector3(1, 1) * Time.deltaTime * 60);
await UniTask.Yield();
}
}
I’ve tested each of them separately. The first call to the coroutine was 1.48ms and 256B of GC Alloc, whereas the UniTask was 6.23ms and 3.2KB of GC Alloc.
Subsequent calls to Coroutines reported 0.02ms and 64B of GC whereas calls to UniTask were 0.04ms and 240B.
Am I doing something wrong? Also, I didn’t even get to the part where I want to cancel active Unitask before starting new ones. With coroutines, I use the same Coroutine variable to check if it’s not null, in which case, you’d stop the current Coroutine variable, and start a new one using that variable (something similar to this):
private Coroutine _coroutine1;
// ...
if(_coroutine1 != null)
{
StopCoroutine(_coroutine1);
}
_coroutine1 = StartCoroutine(Coroutine1());
I think in UniTask you’d use something like CancellationTokenSource bounceAnimationCancellationTokenSource = new CancellationTokenSource();, in which case, I wonder how you would avoid allocating memory. However, I have no idea how this would be implemented, or even if this is the correct thing to achieve something similar.
I’m not sure how things are done in UniTask overall, so if someone can help me out here I’d appreciate it.





(this one 24.62 ms out of nowhere!)







