- Home /
Stop animation when button is released
Hi,
I want my character to "Power Up".
Now, when you press the power up button, it plays the first animation, the loops the appropriate animation. Only problem is, the animation does not stop playing.
I want to let the loop animation play for as long as you press the button down, and when the button is released, it must stop the animation. Any ideas?
Ps. I got the script from another question in this forum.
var PowerUp : String = "PowerUp"; var PowerUpLoop : String = "PowerUpLoop";
function COPowerUp() { var state : AnimationState = animation[PowerUp];
state.wrapMode = WrapMode.ClampForever;
state.speed = 1.0;
animation.Play(PowerUp);
yield new WaitForSeconds(state.length);
animation.Play(PowerUpLoop);
inTransition = false;
}
function Update () { var horizontal = Input.GetAxis("Horizontal"); var vertical = Input.GetAxis("Vertical");
if (Input.GetButtonDown("Power Up")) {
StartCoroutine(COPowerUp());
}
if (Input.GetButtonUp("Power Up")){
StopCoroutine(COPowerUp());
}
}
Answer by Jason_DB · Mar 22, 2011 at 01:22 AM
You could use Animation.Stop right before StopCoroutine. I would also check whether or not the animation is set to loop in the import settings for the animation, which would explain why it wouldn't stop to begin with (and would also mean you wouldn't have to keep replaying it).
Works 100%! Thanks, only prob, when you press the button quickly, and not hold it in, it still loops :( PS. I now NOTHING about this type of code, only starting to learn now.
Answer by Statement · Mar 22, 2011 at 02:42 AM
StopCoroutine accepts a string, so you should not call it the way you do (Or I am missing out on something fun about JS again).
if (Input.GetButtonDown("Power Up")) { StartCoroutine("COPowerUp"); // <- start it by name }
if (Input.GetButtonUp("Power Up")){ StopCoroutine("COPowerUp"); // <- stop it by name }
Also, like DastardlyBanana points out, you should stop the animation with Animation.Stop, since it otherwise would remain in "PowerUp" animation. It also looks like you would want to start the "PowerUpLoop" animation.
It makes sence, but i get the following error: "Assets/Standard Assets/Character Controllers/Sources/Scripts/Powerup2.js(8,10): BCE0089: Type 'Powerup2' already has a definition for 'COPowerUp'."
New to scripting, sorry, but thanks for the help!