Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Resolved Animation Script Error: NullReferenceException

Discussion in 'Scripting' started by Mick_Ash, Nov 15, 2023.

  1. Mick_Ash

    Mick_Ash

    Joined:
    Oct 6, 2023
    Posts:
    28
    Hi, again.

    I am having an issue with my animation for a character walking. When following a tutorial (to the letter) on top-down animation, I run into an error in this code on line 20:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlayerMovement : MonoBehaviour
    6. {
    7.     public float moveSpeed = 5f;
    8.  
    9.     public Rigidbody2D rb;
    10.  
    11.     Vector2 movement;
    12.  
    13.     Animator animator;
    14.  
    15.  
    16.     void Update()
    17.     {
    18.         movement.x = Input.GetAxisRaw("Horizontal");
    19.         movement.y = Input.GetAxisRaw("Vertical");
    20.         animator.SetFloat("Horizontal", movement.x);
    21.         animator.SetFloat("Vertical", movement.y);
    22.         animator.SetFloat("Speed", movement.sqrMagnitude);
    23.     }
    24.  
    25.     void FixedUpdate()
    26.     {
    27.         rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime);  
    28.     }
    29. }
    The error is: "NullReferenceException: Object reference not set to an instance of an object." at line 20; line 20 is "animator.SetFloat("Horizontal", movement.x)

    Does anyone know what the problem is, exactly? Is this a common error? I followed the tutorial to the letter, so I am confused as to why this error appears.
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,162
    It's such a common error that there is a huge post about it!
    https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

    But, to break it down to the three simple steps.
    1. Find out what is null.
    2. Find out why it's null.
    3. Fix it!

    I'll give you a hint. Learn to use Debug.Log or the debugger to step through your code. But, at a glance, animator is probably null since it's a private variable.

    Chances are, nothing is assigned to it. So, that's step 1 and 2! Now go take care of step 3!
     
  3. Mick_Ash

    Mick_Ash

    Joined:
    Oct 6, 2023
    Posts:
    28
    Thank you! I'll set the animator to public and see if it resolves this!
     
  4. Mick_Ash

    Mick_Ash

    Joined:
    Oct 6, 2023
    Posts:
    28
    Fixed! Just had to set the animator to public and assign the animator controller!