Animator not adding to GameObject

I’ve made a sprite, made an animation and attached it. However, on attempting to create a script and make a variable that holds the animator, it doesn’t work.
When I try:

Animator animator = gameObject.GetComponent<Animator>();

it gives me the error “GetComponent requires that the requested component ‘Animator’ derives from MonoBehaviour or Component or is an interface.”
If I try:

public Animator animator;

when returning to the inspector and attempting to drag the component on, nothing happens. The animation is working fine, it just won’t attach to my script.

Thanks in advance!

Could it be that you have a class named Animator? If so you should rename it to something else and that should solve the problem.

You have to be careful about naming your class equally to an already existing one. If you don’t want to change the class name for whatever reason you have to use UnityEngine.Animator from now on if you want to reference the Animator component.