- Home /
Play a simple animation once on key press
I'm experimenting with controlling a little robot player that has an animation to make himself get taller (kind of like a jumping motion). I have saved the animation and it works find when the Animator component loops it through continuously. I would like to instead play this short animation once, until it finishes, on (Input.GetKey(KeyCode.UpArrow))
- is this possible? PS Javascript would be ideal as I'm a beginner :) Thanks!
Answer by Tehnique · Jul 18, 2014 at 12:05 PM
Yes, it is, something like this should do:
animation["YourAnimation"].wrapMode = WrapMode.Once;
...
void Update()
{
if ( Input.GetKey(KeyCode.UpArrow) )
{
StartCoroutine(PlayAnimation());
}
}
...
IEnumerator PlayAnimation()
{
animation.CrossFade("YourAnimation");
animation.Play("YourAnimation");
yield WaitForSeconds (animation["YourAnimation"].length);
}
This looks like what I'm looking for! Just one thing, I tried this and received this error: 'System.Collections.IEnumerator' is not a valid macro.
What might I be missing? Also, when referencing the animation itself, am I putting the name of the animation itself, the animation state, or it's tag? Thanks :)
At what line does that happen? It's probably a typo/missing bracket. You reference the animation by animation name.
Check if you are returning any value in the IEnumerator.
Answer by daviddickball · Jul 18, 2014 at 12:04 PM
Add a flag, so on keypress change isPlaying = true; so that other times you press up it won't reset the animation.
Answer by BlackPanda · Jul 18, 2014 at 12:25 PM
When the animation file is clicked, there's an option to uncheck the 'Loop Time' in the Inspector window. That will do it, I think.