Audio is not played when keyboard is continuously entered

I want to keep playing windy audio when the player is running fast by pressing shift, but I can only hear the audio when I type in the keyboard, and I can’t hear the audio if I keep pressing it. How can I keep playing when I’m pressing shift? I chose Loop just in case, but it doesn’t work.

void Update()
    {
        // Left Shift -> Dash
        if (Input.GetKey(KeyCode.LeftShift))
        {
            dashSound.Play();
            StartCoroutine("Dash");
            // DashLine Active
            Transform dashPos = Camera.main.transform;
            dashLine.SetActive(true);
            Instantiate(dashLine, dashPos);
            // DashDust Active
            dashDust.SetActive(true);

        }
        else
        {
            dashLine.SetActive(false);
            dashDust.SetActive(false);
        }
    }

I believe the reason you can’t hear it is because it restarts every frame so it doesn’t get a chance to play. What you could do is to check if the audio is playing and only set it if it isn’t

if (!dashSound.isPlaying) {
    dashSound.Play();
}

Or you could only play it when the key is initially pressed

if (Input.GetKeyDown(KeyCode.LeftShift))
{
    dashSound.Play();
}
if (Input.GetKey(KeyCode.LeftShift))
{
    //dashSound.Play(); // <- don't do this here
    StartCoroutine("Dash");
    // DashLine Active
    Transform dashPos = Camera.main.transform;
    dashLine.SetActive(true);
    Instantiate(dashLine, dashPos);
    // DashDust Active
    dashDust.SetActive(true);
}
else
{
    dashLine.SetActive(false);
    dashDust.SetActive(false);
}
1 Like

Thanks! Your code was very helpful!!!

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms