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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With