JetBrains / JetBrains/resharper-unity

Attempt to warn about mixed usage of StartCoroutine and StopCoroutine

Open
#140 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
C#
Stars
1.2k
Forks
142
PR merge metrics
No merged PRs in 30d

Description

This is a slightly complex one to detect but would help catch some nasty unforeseen issues, like the one I just hit! :)

As noted [here](https://docs.unity3d.com/ScriptReference/MonoBehaviour.StopCoroutine.html):

> StopCoroutine takes one of two arguments which specify which coroutine is stopped:
>
> - A string function naming the active coroutine
> - The IEnumerator variable used earlier to create the coroutine.
>
> Note: Do not mix the two arguments. If a string is used as the argument in StartCoroutine, use the string in StopCoroutine. Similarly, use the IEnumerator in both StartCoroutine and StopCoroutine.

As an example the following will cause issues as the coroutine is actually never stopped correctly:

using System.Collections;
using UnityEngine;

public class TaskRunner : MonoBehaviour
{
private bool isRunning = false;

public void Toggle()
{
isRunning = !isRunning;

if (isRunning)
{
StartCoroutine(MyRoutine("go to the shops"));
}
else
{
StopCoroutine("MyRoutine");
}
}

IEnumerator MyRoutine(string task)
{
while (true)
{
Debug.LogFormat("I'm running task {0}", task);
yield return null;
}
}
}

The suggested code fix in this instance would be to save the IEnumerator in a private variable as follows:

using System.Collections;
using UnityEngine;

public class TaskRunner : MonoBehaviour
{
private bool isRunning = false;
private IEnumerator myRoutineEnumerator;

public void Toggle()
{
isRunning = !isRunning;

if (isRunning)
{
myRoutineEnumerator = MyRoutine("go to the shops");
StartCoroutine(myRoutineEnumerator);
}
else
{
StopCoroutine(myRoutineEnumerator);
}
}

IEnumerator MyRoutine(string task)
{
while (true)
{
Debug.LogFormat("I'm running task {0}", task);
yield return null;
}
}
}

Not sure what the scope of implementing this fix would be, but thought it would be a useful issue to flag up :)

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.