Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unity C# Play an animation once on key

I have 2 attack animations named "attacking_1" and "attacking_2", I want to play one at random when player presses "C" key once. I want the animation to continue to play to last frame of it without player needing to hold down the C key.

Here’s my code and what’s happening is that this code is ran every frame and making my player display both attack animations on one C key press.

What I don’t understand is why the if statement is executing many times even tho the player only press the C key once.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

   if (Input.GetKey(KeyCode.C))
    {
        int random = Random.Range(1, 3);
        Debug.Log(random);
        anim.SetBool("attacking_" + random.ToString(), true);
    }

>Solution :

"Input.GetKey()"
Checks if a button is pressed down every frame and runs it every frame. What you need is
"Input.GetKeyDown()"
Which only runs it the first frame it’s pressed down

Hope this helps!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading