>
>
>
V3213. Unity Engine. The 'GetComponent'…


V3213. Unity Engine. The 'GetComponent' method must be instantiated with a type that inherits from 'UnityEngine.Component'.

The analyzer has detected that the argument to the GetComponent method (or similar) of the Component or GameObject classes is passed as a type that neither inherits from UnityEngine.Component nor is an interface. In such cases, the method always returns null or throws an exception. The use of these methods in this way must be avoided.

Look at the example:

struct CameraAnchorData : IComponentData {}

class CameraController: MonoBehaviour
{
  ....
  public GameObject Target;

  private void Start()
  {
    if (Target.TryGetComponent<CameraAnchorData>(out var anchor))
    {
      ....
    }
  }
}

The TryGetComponent method uses CameraAnchorData as a generic argument, but this type does not inherit from UnityEngine.Component. Calling the method will always result in an exception.

Besides generic arguments, an invalid component type can also be passed as a simple argument:

struct CameraAnchorData : IComponentData {}

class CameraController: MonoBehaviour
{
  ....
  public GameObject Target;

  private void Start()
  {
    if (Target.TryGetComponent(typeof(CameraAnchorData), out var anchor))
    {
      ....
    }
  }
}

Calling the TryGetComponent method with typeof(CameraAnchorData) as a simple argument will also result in an exception.

This diagnostic is classified as: