Hi,
I want to know how i can put the sound in loop while the player is walking. I use for example Input.GetKey(KeyCode.RightArrow) but if i’m pressing the right key the sound only play once. Can you help me?
Thank you
Alberto
ChatGPT
using UnityEngine;
[RequireComponent(typeof(AudioSource))]
public class PlayerWalkSound : MonoBehaviour
{
private AudioSource audioSource;
private bool isWalking = false;
// Unity's predefined keycodes for basic movement
private KeyCode[] walkKeys =
{
KeyCode.W,
KeyCode.A,
KeyCode.S,
KeyCode.D,
KeyCode.UpArrow,
KeyCode.LeftArrow,
KeyCode.DownArrow,
KeyCode.RightArrow
};
private void Awake()
{
audioSource = GetComponent<AudioSource>();
audioSource.loop = true; // Make sure the sound loops
}
private void Update()
{
bool currentWalkingState = IsWalkingKeyActive();
// If state changed from not walking to walking, play sound
if (currentWalkingState && !isWalking)
{
audioSource.Play();
}
// If state changed from walking to not walking, stop sound
else if (!currentWalkingState && isWalking)
{
audioSource.Stop();
}
isWalking = currentWalkingState;
}
private bool IsWalkingKeyActive()
{
foreach (KeyCode key in walkKeys)
{
if (Input.GetKey(key))
{
return true;
}
}
return false;
}
}
2 Likes
I think the 2nd tutorial named “Create dynamic sound effects” from the Audio mission of Creative Core leaning section is exactly what you need.
Attach sound source to the character. It has property “looping” or similar one somewhere. Set it to true. Begin playing when player moves, stop playing when it stops. That’s it.
Note that in this case step sounds will probably mismatch step times when character puts foot on the ground. Depending on the genre it might not matter and might not be noticeable.
1 Like
Thank you