- Home /
Playing audio loop only when moving character controller
Hi guys, I'm trying to make mycharacter play a loop of audio only when they are walking. Here is my code but it is not working. Seems to produce a stuttering effect:
public AudioSource PlayerAudioSource1;
if(Input.GetButton("Vertical")){
if(!PlayerAudioSource1.isPlaying) {PlayerAudioSource1.Play();}
} else {
PlayerAudioSource1.Stop();
}
if(Input.GetButton("Horizontal"))
{
if(!PlayerAudioSource1.isPlaying) {PlayerAudioSource1.Play()}
} else {
PlayerAudioSource1.Stop();
}
Does anyone know how to resolve this?
Answer by aurelioprovedo · Dec 19, 2017 at 10:49 AM
The conditions are wrongly nested. With your code, you are stopping the audio if it is playing. You want to stop the audio if the character is not moving.
Use this code instead:
// If the user is pressing any of the move buttons:
if (Input.GetButton("Vertical") || Input.GetButton("Horizontal"))
{
if (!PlayerAudioSource1.isPlaying)
{
PlayerAudioSource1.Play();
}
}
else
{
// Always stop the audio if the player is not inputting movement.
PlayerAudioSource1.Stop();
}
Advice: always make sure you use correct indentations. Otherwise, your code will get confusing to read, and this type of errors will often happen to you.
Your answer
Follow this Question
Related Questions
I want to play an Audio Sound for a character while running. 0 Answers
Make characters go through each other 1 Answer
2D character bounce off wall / shakes while walking into it 3 Answers
add constant z axis movement to third person / character controller 5 Answers
Creating a platform game on 2 axis. Should I use a rigid body, or a character controller. 1 Answer