Input.GetKey working only once

Hi,
I’m trying to make my first game, but I can’t get the character to return to the idle animation.

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour
{
    Animator animator;
    public float moveSpeed;
    public int State =0;

    void Start()
    {
        animator = GetComponent<Animator>();
    }

    void Update()
    {
        State = 0;
        if (Input.GetKey(KeyCode.D))
        {
            GetComponent<Rigidbody2D>().velocity = new Vector2(moveSpeed, GetComponent<Rigidbody2D>().velocity.y);
            State = 1;
            animator.SetInteger("State", State);
        }

        if (Input.GetKey(KeyCode.A))
        {
            GetComponent<Rigidbody2D>().velocity = new Vector2(-moveSpeed, GetComponent<Rigidbody2D>().velocity.y);
            State = -1;
            animator.SetInteger("State", State);
        }

    }
}

whare moveSpeed is the set speed at which the character moves, and State is used to determine if the player is idle, walking left or right . The character starts idle, but whenever I press A or D, the character gets stuck in the walk animation. Also, the animation is set to transition when State == 0 and State !=0

Notice that if you aren’t pressing down a key, you set State to 0. However, you never use animator.SetInteger().
Do this instead:

void Update()
    {
        State = 0;
        if (Input.GetKey(KeyCode.D))
        {
            GetComponent<Rigidbody2D>().velocity = new Vector2(moveSpeed, GetComponent<Rigidbody2D>().velocity.y);
            State = 1;
        }
        if (Input.GetKey(KeyCode.A))
        {
            GetComponent<Rigidbody2D>().velocity = new Vector2(-moveSpeed, GetComponent<Rigidbody2D>().velocity.y);
            State = -1;
        }
         animator.SetInteger("State", State);
    }
1 Like