pressing a key to play an animation {SOLVED}

hey, for part of a game im making for college i want the player to be able to press the ‘E’ key to drop an object, this will be will be shown as an animation - i have no idea as to how id write the code for the player pressing E to play the animation in C#, if anyone has any tips or tutorials that would be great.
also, i want the player to only be able to press the E key when inside a trigger.

Thanks for all the help in advance, im new to C# and the unity forums and all the help ive received so far has been great. :smile:

http://unity3d.com/learn/tutorials/modules/beginner/scripting/get-button-and-get-key?playlist=17117
http://unity3d.com/learn/tutorials/modules/beginner/animation/animator-scripting?playlist=17099

Thanks for the tutorials, i had a look at these and some more around the web and i tried this but it isn’t working and i get no error messages, have i done anything in particular wrong?

if (myBool) {
            if (Input.GetKeyDown (KeyCode.E)) {
                myAnimator.SetBool ("vine", true);
                Debug.Log ("should be working");

is KeyCode.E the right thing to use here? i know that my animations all work fine because i tested them out beforehand. Thanks for all the help. :slight_smile:

Does it log?
Is the animator graph set up correctly
Script applied to gameobject?

it doesn’t log, the graph is set up and working and i have applied the script to a trigger, as i want the player to need to be inside the trigger and press E for this animation to work
its applied onto my trigger, does it need to be applied to the thing i am animating also?

I changed this to on mouse down and did it this way instead and it worked, im presuming unity just wouldnt allow it or i had some code somewhere that contradicted with it, thanks for the help anyways!

When you say you applied the script to a trigger, what do you mean? It really helps if you post the entire script, or at least the entire method, that you’re talking about.

I’m guessing that you put it inside the OnTriggerEnter function. In that case, the reason it didn’t appear to work is, the user would have to press the E key on exactly the same frame as entering the trigger. At 60 frames/second, that’s pretty much impossible to do!

Code like this should be in the Update method, and if you need to check something else (like the state of a trigger), just set a boolean property when the user enters/exits the trigger, and then check that boolean in addition to the keypress.

I put the script on the object that contained the trigger that the player needed to be inside to press E, sorry about that, I’ll post the code next time, thank you!
The script wasn’t inside the update function so im guessing that’s why it didn’t work, thank you again! :slight_smile:

1 Like