- Home /
Stop one animation while another plays
Hey everyone ive been getting a problem where I have a walk animation and an attack animation on the same object (sword) For some reason when I walk and use the attack button the swing animation I use bugs out with the walking animation.
Is there a way to stop one animation while another plays? With my game its pretty important that the swing happens at the moment the button is pressed. I've tried a few things but the code I have up to now doesn't work.
if(Input.GetMouseButtonDown(0)){
sword.animation.Stop("walk");
sword.animation.Play("attack1");
}
else if(Input.GetAxis("Vertical"))
{
sword.animation.CrossFade("walk");
}
else if(Input.GetAxis("Horizontal"))
{
sword.animation.CrossFade("walk");
}
else
{
sword.animation.Stop("walk");
}
Would anyone be able to tell me what is wrong and how I can fix this?
Answer by Waz · Aug 25, 2011 at 03:19 AM
With the above code, executing every frame in an Update()
function, if you walk and while walking press the mouse, this happens:
walk animation plays
walk stops, attack1 plays
walk animation crossfades in again the very next frame
I'm guessing you haven't read the Animation Scripting documentation, since it covers this exact case in the "Animation Layers" section.
Reading is good.
Answer by track01 · Aug 25, 2011 at 03:39 AM
Thank you, I've gotten it working now :)
If anyone needs the new code:
var sword : GameObject;
function Start() {
// Set all animations to loop
sword.animation.wrapMode = WrapMode.Loop;
// except shooting
sword.animation["attack1"].wrapMode = WrapMode.Once;
// Put idle and walk into lower layers (The default layer is always 0)
// This will do two things
// - Since shoot and idle/walk are in different layers they will not affect
// each other's playback when calling CrossFade.
// - Since shoot is in a higher layer, the animation will replace idle/walk
// animations when faded in.
sword.animation["attack1"].layer = 1;
// Stop animations that are already playing
//(In case user forgot to disable play automatically)
sword.animation.Stop();
}
function Update() {
// Based on the key that is pressed,
// play the walk animation or the idle animation
if (Input.GetAxis("Vertical"))
sword.animation.CrossFade("walk");
else if(Input.GetAxis("Horizontal"))
{
sword.animation.Play("walk");
}
// Shoot
if(Input.GetMouseButtonDown(0))
sword.animation.CrossFade("attack1");
}
this just fixed a big problem I was having in my script. I had the same exact issue and layering them properly in my code is what fixed it. All I had to do was put my animation 1 layer above the other and voila, it works. thanks for the info!
Your answer
Follow this Question
Related Questions
ANimation doesn't rewind on animation.Stop 3 Answers
Animation Finished 1 Answer
Can the animation editor create local rotational data? 3 Answers
Adding animation clips via script 2 Answers
Detect if is playing an animation 1 Answer