'Animations problems c# unity

I've been trying to create a game on unity and while I was trying to do the animations I'm realizing that I don't have any idea why my code is not working.

//Animacion
if(!Input.GetKey("left") && !Input.GetKey("right"))
{
    gameObject.GetComponent<Animator>().SetBool("Moving", false);            
}

if(Input.GetKey("right"))
{
     gameObject.GetComponent<Animator>().SetBool("Moving", true);            
}

if(Input.GetKey("left"))
{
     gameObject.GetComponent<Animator>().SetBool("Moving", true);            
}

I am not getting any error



Solution 1:[1]

You can just simply use this instead:

gameObject.GetComponent<Animator>().SetBool("Moving", Input.GetAxis("Horizontal") != 0);

But to fix your own code you can do this:

if (!Input.GetKey(KeyCode.LeftArrow) && !Input.GetKey(KeyCode.RightArrow))
{
    gameObject.GetComponent<Animator>().SetBool("Moving", false);
}
if (Input.GetKey(KeyCode.RightArrow))
{
    gameObject.GetComponent<Animator>().SetBool("Moving", true);
}
if (Input.GetKey(KeyCode.LeftArrow))
{
    gameObject.GetComponent<Animator>().SetBool("Moving", true);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Armin