Need help with enemy animtation triggering

Hi im making a top down survival shooting game, i have put the enemy, idle, attack and walk animations into the animator controller for the enemy object, in the enemy script which moves the enemy towards the player i am trying to link it to the animator with no success.

using UnityEngine;
using System.Collections;

public class Enemy : MonoBehaviour {

    Animator anim;
    public Transform target;
    public float speed = 20f;
    private float minDistance = 1f;
    private float range;
   

    void Update ()
    {
        Movement ();
    }

    void Movement()
    {
        range = Vector2.Distance(transform.position, target.position);
       
        if (range > minDistance)
        {
            Debug.Log(range);
           
            transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
            anim.SetFloat("Speed", speed);
        }


    }
}

That is my script, but i receive the error,
NullReferenceException: Object reference not set to an instance of an object
Enemy.Update () (at Assets/Scripts/Enemy.cs:17)

Any help with this would be greatly appreciated im a beginner with unity

Null Reference Exception means that you have a variable that represents a specific object, and you try to use that variable but it is empty (or null).

In your class, you have object references to Animator (anim), and Transform (target). So those are your two potential null references.

Since your “target” variable is public, I’m assuming you set that in the inspector so it is not empty (null).

Your “anim” variable is private however (if you don’t give it a keyword, it’s automatically private). Which means that you need to get that Animator reference thru code, or else that variable will be forever empty.

So you have two options for “anim”. Make it public, and drag the component, or object that has the component into the inspector just like for “target”. Or use an initialization function (Awake or Start) to assign your “anim” variable using GetComponent() or similar.

Example:

// called by Unity when this object loads
private void Awake()
{
    anim = GetComponent<Animator>(); // searches this GameObject for an Animator component
}

You can prevent Null Reference Exceptions by checking if your variables are null before using them.

Example:

if(anim != null)
{
    anim.SetFloat("Speed", speed);
}
else
{
    Debug.LogWarning("Animator component missing!");
}