UNT0016 Unsafe way to get the method name
June 2, 2024 ยท View on GitHub
Using Invoke, InvokeRepeating, CancelInvoke, StartCoroutine or StopCoroutine with a first argument being a string literal is not type safe. Instead it's recommended to use the nameof operator or a direct call for coroutines. The further benefit of doing this is the ability for the method to use a rename refactoring without remembering to update the string literals.
Examples of patterns that are flagged by this analyzer
using UnityEngine;
using System.Collections;
class Camera : MonoBehaviour
{
void Start()
{
Invoke("InvokeMe", 10.0f)
StartCoroutine("MyCoroutine");
}
private void InvokeMe()
{
// ...
}
private IEnumerator MyCoroutine()
{
// ...
}
}
Solution
Use nameof or direct call for coroutines.
using UnityEngine;
using System.Collections;
class Camera : MonoBehaviour
{
void Start()
{
Invoke(nameof(InvokeMe), 10.0f)
StartCoroutine(MyCoroutine());
}
private void InvokeMe()
{
// ...
}
private IEnumerator MyCoroutine()
{
// ...
}
}
Code fixes are offered for this diagnostic to automatically apply those changes.