- Home /
Sound effect doesn't play correctly
Hello, I'm making a 2D platformer game and I have a gliding mechanic. I want there to be a sound effect that plays while the player is gliding but for some reason, the code I used has the sound playing after the player lets go of the gliding button instead of while it's held down. Here is my code:
isGliding = false;
if (Input.GetButton("Jump") && rb.velocity.y < 0 && abilities.canGlide)
{
isGliding = true;
rb.velocity = new Vector2(rb.velocity.x, -glidingSpeed);
PlayerAudio.instance.PlaySFX(1);
}
I'm using a script that has an array of sounds so you can play a sound by passing in the correct index. Any help would be appreciated and thank you in advance.
Answer by MickyX · May 03 at 03:17 PM
I think this would call the PlaySFX every frame that "Jump" is held down , so what you are probably seeing (or hearing) here is the sound effect constantly starting and the start of the clip is probably silence.
Then when you let go the audiosource has the chance and plays the rest of the clip
You need to do something like see if the clip is already playing before asking it to play the clip again, or only call the SFX once if it is looping
Not sure how your input is working, but if you only want it to play while Jump is held down you could probably do something simple like
if (Input.GetButton("Jump") && rb.velocity.y < 0 && abilities.canGlide)
{
if(!isGliding)
PlayerAudio.instance.PlaySFX(1);
isGliding = true;
rb.velocity = new Vector2(rb.velocity.x, -glidingSpeed);
}
else
{
isGliding = false;
}
I moved the isGliding = false into the else because otherwise it would reset everytime and still call the audio.
I think this answer is correct: GetButton()
is called every frame the button is 'down', which will be for multiple frames. Consider GetButtonDown()
, as it is only called on the single frame in which the button enters the 'down' state.
GetButton: https://docs.unity3d.com/ScriptReference/Input.GetButton.html GetButtonDown: https://docs.unity3d.com/ScriptReference/Input.GetButtonDown.html