Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity 3D: Footstep sounds looping the first few milliseconds instead of playing the full sound then looping

When I move in game, instead of my sound being played in full, it is playing just a few milliseconds on a loop.

Here's my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Footsteps : MonoBehaviour
{
    public AudioSource audioSource;

    public PlayerMovement pM;

    void Start()
    {
        audioSource.Stop();
    }

    void Update()
    {
        PlaySound();
    }

    public void PlaySound()
    {
        if (Input.GetKey(KeyCode.W))
        {
            audioSource.Play();
        }
        else
        {
            audioSource.Stop();
        }
    }
}

Video Example.

Any suggestions would be greatly appreciated!

like image 264
Ne0 Avatar asked Jan 31 '26 22:01

Ne0


1 Answers

The method Input.GetKey() is called as long as the key is pressed. To do that you want, you could use Input.GetKeyDown() like this example:

    public void PlaySound()
        {
            if (Input.GetKeyDown(KeyCode.W))
            {
                audioSource.Play();
            }
            else if(Input.GetKeyUp(KeyCode.W))
            {
                audioSource.Stop();
            }
        }

There are other ways to to this kind of sounds, but this simple way should work.

References:

https://docs.unity3d.com/ScriptReference/Input.GetKey.html https://docs.unity3d.com/ScriptReference/Input.GetKeyDown.html

like image 185
Jamarin Avatar answered Feb 02 '26 14:02

Jamarin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!