>
>
>
V3215. Unity Engine. Passing a method n…


V3215. Unity Engine. Passing a method name as a string literal into the 'StartCoroutine' is unreliable.

The analyzer has detected that a string literal is passed as an argument to the Invoke, InvokeRepeating, CancelInvoke, StartCoroutine, or StopCoroutine methods of the UnityEngine.MonoBehaviour class, which is unreliable. If the passed string literal no longer corresponds to the method for some reason—in particular, if the method changes its name or becomes unavailable—the call will be ignored without any notification.

The example:

public class CoroutineAndInvoke : MonoBehaviour
{
  void Start()
  {
    Invoke("CreateEnemyMethod", 1f);
    StartCoroutine("DangerCheckCoroutine");
  }

  private void CreateEnemyMethod()
  {
    ....
  }

  private IEnumerator DangerCheckCoroutine()
  {
    ....
  }
}

In this case, the Invoke and StartCoroutine methods are called with string literals that correspond to the existing methods, CreateEnemyMethod and DangerCheckCoroutine. The script works correctly, but reliability is broken. As the result, the analyzer issues a level 3 warning.

To maintain reliability when calling these methods, use nameof to retrieve the method name. If you use StartCoroutine, call the coroutine directly.

The example with the maintained reliability:

public class CoroutineAndInvoke : MonoBehaviour
{
  void Start()
  {
    Invoke(nameof(CreateEnemyMethod), 1f);
    StartCoroutine(DangerCheckCoroutine());
  }
  ....
}

In this case, passing a non-existent method as an argument is prevented. Another advantage of using nameof and direct coroutine calls is the ability to rename methods during refactoring. The changes automatically update the arguments of the Invoke and StartCoroutine methods.

Here is an example where string literals do not correspond to the methods:

public class CoroutineAndInvoke : MonoBehaviour
{
  void Start()
  {
    Invoke("CreateEnemy", 1f);
    StartCoroutine("DangerCheck");
  }

  private void CreateEnemyMethod()
  {
    ....
  }

  private IEnumerator DangerCheckCoroutine()
  {
    ....
  }
}

In this case, the Invoke and StartCoroutine methods are ignored because no methods corresponding to the passed string literals are detected. The analyzer issues a level 1 warning. Such an error can occur, for example, due to a typo when writing the method name in the argument or when renaming the method.

This diagnostic is classified as: