Null Exception on working script using AI and Animator

Ran into an issue last night with my AI script (which was working). The issue has caused the script to stop working and there are no changes to the script, which is why this issue is odd for me. Note: I have removed most variables and unnecessary code.

NullReferenceException: Object reference not set to an instance of an object
AI.UpdateAnimator () (at Assets/My Stuff/My scripts/AI.cs:122)
AI.Update () (at Assets/My Stuff/My scripts/AI.cs:54)

I will show the 3 parts of concern:

using UnityEngine;
using UnityEngine.AI;


public class AI : MonoBehaviour
{
    #region Variables


    public float lookRadius = 10f;

    Transform target;
    NavMeshAgent agent;
    Animator animator;
    GameObject PlayerObj;


    public int maxHealth = 200;
    public int health = 200;
    public int minHealth = 0;

    public float deathWait = 0.03f;

    public bool isDead = false;



   public bool isHitting;

    #endregion


    void Start()
    {

        PlayerObj = GameObject.FindGameObjectWithTag("Player");
       agent = GetComponent<NavMeshAgent>();
        target = PlayerManager.instance.player.transform;
        animator = GetComponent<Animator>();
        health = maxHealth;

    }


    void Update()
    {
        isHitting = PlayerObj.GetComponentInChildren<Controls>().swinging;
        if (isDead == false)
        {
            Debug.Log("Is Start");
            UpdateAnimator();
            float distance = Vector3.Distance(target.position, transform.position);

            if (distance <= lookRadius)
            {
                agent.SetDestination(target.position);

                if (distance <= agent.stoppingDistance)
                {
                    FaceTarget();

                    Attack();

                }

            }
        }
        if (health <= minHealth)
        {

            isDead = true;
            Invoke("Die", deathWait);
        }



    }

    private void Attack()
    {
       int DMG = GetComponentInChildren<WeaponItem>().weaponItem.weaponDMG;
        animator.SetTrigger("Attack");
    }

    void Die()
    {
        if (isDead)
        {

            animator.SetBool("Die", true);
            animator.ResetTrigger("Attack");

        }
    }

    void FaceTarget()
    {
        Vector3 direction = (target.position - transform.position).normalized;
        Quaternion lookRotation = Quaternion.LookRotation(new Vector3(direction.x, 0, direction.z));
        transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * 5f);
        Debug.Log("Looking at player");
    }

    #region Gizmos
    private void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawWireSphere(transform.position, lookRadius);
    }

    #endregion

   private void UpdateAnimator()
    {
        Debug.Log("Moving by animation");
        Vector3 velocity = agent.velocity;
        Vector3 localVelocity = transform.InverseTransformDirection(velocity);
        float speed = localVelocity.z;
        animator.SetFloat("MoveSpeed", speed);
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Axe") && isHitting)
        {
            health -= PlayerObj.GetComponentInChildren<WeaponItem>().weaponItem.weaponDMG;
            health = Mathf.Clamp(health, 0, maxHealth);

            Debug.Log(health);
        }

        if (other.CompareTag("PickAxe"))
        {
            Debug.Log(health);
        }

        if (other.CompareTag("Sword"))
        {
            Debug.Log(health);
        }


    }


}

The variables are already defined and in their correct location at the top of the script or within a local scope. The script was working for about a week, with the only change being a SendMessage() to another script in an unaffected if statement.

The editor also gave a null exception for this line when I removed UpdateAnimator():
float distance = Vector3.Distance(target.position, transform.position);

Can anyone tell what's the issue? My Animator has the proper parameters "MoveSpeed" using a blend tree and was working fine. The Debug.Log in UpdateAnimator() does run, and line number for the error rests at: animator.SetFloat("MoveSpeed", speed);

Could you show the whole script?

there is an error at 122 and 54, your script doesnt provide those lines

Line 122 here is line 43.

Line 54 here is line 18.

Give me a moment and I'll edit the post to include the full script

the animator is null , looks to me,

do you have an animator script on your component?

The GameObject has an Animator component and the AI.cs script, along with the animator controller. Script has been updated.

try something like that:

if(animator) {
        animator.SetFloat("MoveSpeed", speed);
} else {
        print("Animator Component not attached");
}
1 Like

That's a good one. Yep, it's saying it's not attached.

try to get your components in "Awake",

and add something like that to your class, after saving the class, remove the component from your gameobject and reattach it to it

[RequireComponent(typeOf(Animator))
public class AI : MonoBehaviour

you need to check if its right written since im writing in here in the browser

Awesome, thanks! Only when I moved the Start() code to Awake did it finally work. Weird. Thanks again!

2 Likes

There is likely a reason and you can ultimately figure out, if you care… check this out:

Here is some timing diagram help:

ALSO… for any nullref you might encounter in the future (AND YOU WILL! :slight_smile: ), the key is to get over it fast. Here’s some more reading:

Some notes on how to fix a NullReferenceException error in Unity3D

  • also known as: Unassigned Reference Exception
  • also known as: Missing Reference Exception

http://plbm.com/?p=221

The basic steps outlined above are:

  • Identify what is null
  • Identify why it is null
  • Fix that.

Expect to see this error a LOT. It’s easily the most common thing to do when working. Learn how to fix it rapidly. It’s easy. See the above link for more tips.

2 Likes