- Home /
How can I trigger an animation to play at a certain frame in another animation?
Hello all! I've hit a bit of a bump in the road on this particular project of mine, and thought I'd turn to Unity Answers for help.
Basically I have this walk animation that plays when the 'W' key is being held. And I want a jump animation to interrupt it when the 'space' key is hit. The thing that I'm struggling with though is making the jump animation play at the 10th frame of the walk animation. What I mean is I want the animation to continue playing and then play the jump animation at the 10th frame. I tried using a while loop to make the jump animation yield until the walk animation got to the tenth frame, but it isn't working. Here's the code:
var forwardspeed:float=.5;
animation["run"].speed=1.4; animation["walk"].speed=.1;
function Update (){ animation.CrossFade ("idle");
if(Input.GetKey(KeyCode.W)){
directionforward=Vector3.forward*forwardspeed*Time.deltaTime; transform.Translate(directionforward*forwardspeed); animation.CrossFade ("walk"); if(Input.GetKey(KeyCode.Space)) {
//plays the "walk jump" (jump specific to the walk)
walk_Jump();
}
}
function walk_Jump(){
//frames per second=24 This bit of code gets the current frame
var animationLengthWalk=animation["walk"].length;
var framelength=animationLengthWalk/20;
var animationLengthJump=animation["jump"].length;
var currentTime= animation["walk"].time % animationLengthWalk;
var currentFrame= currentTime*24;
if(currentFrame!==10){ //this should continue yielding until the walk animation's current frame equals 10 while(currentFrame!==10){ yield; }
animation.Play("jump"); yield WaitForSeconds(animationLengthJump);
}
else{
animation.Play("jump");
yield WaitForSeconds(animationLengthJump);
}
}
What am I doing wrong here? Thanks in advance!
Answer by Seth-Bergman · Jul 28, 2012 at 02:34 AM
The best way I know is using animation.normalizedTime
this is a float from 0 (the first frame) to 1 (the last frame)
animation.length returns a float length in seconds
not what you want here
just say
if(animation["walk"].normalizedTime >= .3) // or whatever
{
//jump!
}
desired frame / total frames
the issue is more getting the animation to play at that exact time...and waiting to play until it gets to that time. So for example, if I hit the 'jump' button at frame 3 of the walk animation, I want the walk animation to continue playing until it gets to frame 10, and then jump. I have the whole frame thing worked out, it's just getting the jump animation to wait...
Your answer
![](https://koobas.hobune.stream/wayback/20220613074819im_/https://answers.unity.com/themes/thub/images/avi.jpg)