Search Unity

Can't get animator.SetInteger to work.

Discussion in 'Animation' started by Jbergeon649, Jun 29, 2021.

  1. Jbergeon649

    Jbergeon649

    Joined:
    Sep 8, 2020
    Posts:
    8
    I'm trying to use Animator Controller component to transition from Idle animation to walking animation. I can't seem to get animator.SetInteger to work for me. I've tried it with and without the else statement. It works if I put it in the start funtion, but I need it to be tied to the walking input. Movement works fine and through the public float I can see the verticalInput changing when I press the key. Also everywhere I've looked and every video does it just like this with no problems.

    No compiler errors, but Unity throws this error when I hit play: NullReferenceException: Object reference not set to an instance of an object.

    Movement still works fine with play, just no animation unless I change the "Condition" parameter manually through the component.

    I also tried Debug.Log(animator.GetInteger("Condition")), but I guess it doesn't work like that.

    Here's my script:

    Code (CSharp):
    1. public class PlayerController : MonoBehaviour
    2. {
    3.     public float speed = 8;
    4.     public float rotationalSpeed = 45;
    5.  
    6.     public float verticalInput;
    7.     private float rotationalInput;
    8.  
    9.     private Animator animator;
    10.  
    11.  
    12.     void Start()
    13.     {
    14.         Animator animator = GetComponent<Animator>();
    15.         //animator.SetInteger("Condition", 1);
    16.     }
    17.  
    18.     void Update()
    19.     {
    20.         verticalInput = Input.GetAxis("Vertical");
    21.         rotationalInput = Input.GetAxis("Horizontal");
    22.  
    23.         transform.Translate(Vector3.forward * verticalInput * speed * Time.deltaTime);
    24.         transform.Rotate(Vector3.up * rotationalInput * rotationalSpeed * Time.deltaTime);
    25.  
    26.      
    27.         if (verticalInput != 0)
    28.         {
    29.             animator.SetInteger("Condition", 1);
    30.         }
    31.         else
    32.         {
    33.             animator.SetInteger("Condition", 0);
    34.         }
    35.      
    36.     }
    37. }
    Any Ideas to what I'm doing wrong here?
     
  2. Epsilon_Delta

    Epsilon_Delta

    Joined:
    Mar 14, 2018
    Posts:
    135
    It's because you are cashing the animator in a local variable. Drop the "Animator" on the line 14.
    Like this:
    animator = GetComponent<Animator>();
     
unityunity