- Home /
How can I stop animation and sound clip looping on tapCount
Hi there,
I have created a basic animation of my player (capsule) spinning when a button is pressed. I have also told a sound clip to play when the same button is pressed. I am developing my game for the iOS platform, so have used the Camera Relative Control setups, and given this animation + sound button the joystick script. Both the animation and sound clip play, but they are repeated until the button is released. Does anyone know how to make these clips play only once per tapCount?
Code is below:
var rightJoystick : Joystick;
var sound : AudioClip;
function Update()
{
if (rightJoystick.tapCount == 1 )
{
//Play Kill animation
AudioSource.PlayClipAtPoint(sound, transform.position);
animation["kill"].wrapMode = WrapMode.Once;
animation.Play("kill");
}
}
This script is attached to the player, which the animation is also attached to. The script has the same effect with or without: animation["kill"].wrapMode = WrapMode.Once;
If anyone could help out it would be much appreciated!
Thanks
Answer by Codetastic · Dec 29, 2012 at 05:42 AM
Looking at the script 2 problems should be visible:
1) AudioSource.PlayClipAtPoint(sound, transform.position); Would be played over and over every frame thus creating a large number of audio sources.
2) animation.Play("kill"); Is also played over and over each frame. However it looks like it is looping because animation.Play() does not restart the current animation if the animation is already playing, and so when the animation does end it plays it yet again. See Animation.Play() Description 4th sentence: "If the animation is already playing, other animations will be stopped but the animation will not rewind to the beginning"
So all this is happening because you are telling it to do so in Update() (Update happens every frame). Thankfully all you need to fix this is to check if the joystick was just pressed or has bin down already like so:
#pragma strict
var rightJoystick : Joystick;
var sound : AudioClip;
private var isJoystickDownAlready : boolean = false;
function Update(){
if(rightJoystick.tapCount > 0 && isJoystickDownAlready == false){ //if more then 0 we are being pushed
//Set isJoystickDownAlready to true as rightJoystick was just being pushed down. This will only happen once the button is pushed because in the above line we check if isJoystickDownAlready is set to false
isJoystickDownAlready = true;
//Play Kill animation
AudioSource.PlayClipAtPoint(sound, transform.position);
animation["kill"].wrapMode = WrapMode.Once;
animation.Play("kill");
}else if(rightJoystick.tapCount == 0){
//Once rightJoystick is released, tapCount should become 0 so now now if tapCount is 0 set isJoystickDownAlready to false because the rightJoystick is no longer down
isJoystickDownAlready = false;
}
}