Code inspection: Expected a type derived from 'Component' or 'MonoBehaviour'
The Unity.ExpectedComponent inspection ensures type safety when using string-based Unity APIs, such as GameObject.AddComponent(string) and GameObject.GetComponent(string). It flags cases where a specified type exists but does not inherit from the required base class (UnityEngine.Component for built-in types or UnityEngine.MonoBehaviour for user-defined types).
How it works
The inspection uses Unity-specific reference providers to resolve the string literal to a type in the project or libraries. Once the type is resolved, the analyzer checks if it satisfies the inheritance requirements of the method being called.
Validation rules:
For built-in types (from Unity assemblies): The type must derive from
UnityEngine.Component.For user-defined types (in the current project): The type must derive from
UnityEngine.MonoBehaviour.
This prevents runtime errors or silent failures where Unity would be unable to add or find the specified component because it doesn't match the expected signature.
Example
In this example, MyPlainClass does not inherit from MonoBehaviour, so it cannot be added as a component to a GameObject.