using System.Collections.Generic; using UnityEngine; namespace FootstepTutorial { public class FootstepAudio : MonoBehaviour { public AudioClip[] leftFootsteps, rightFootsteps; public Transform leftFoot, rightFoot; [Range(0, 1)] public float volume = 0.65f; [Min(0.01f)] public float minDistance = 1f, maxDistance = 15f; readonly List leftBag = new(), rightBag = new(); // Animation Event integer: 0 = left foot, 1 = right foot. public void PlayFootstep(int foot) { var clips = foot == 0 ? leftFootsteps : rightFootsteps; var bag = foot == 0 ? leftBag : rightBag; if (clips == null || clips.Length == 0) return; // Each foot uses all its clips before starting another random cycle. if (bag.Count == 0) foreach (var clip in clips) if (clip) bag.Add(clip); if (bag.Count == 0) return; int index = Random.Range(0, bag.Count); var selected = bag[index]; bag.RemoveAt(index); Transform origin = foot == 0 ? leftFoot : rightFoot; var soundObject = new GameObject(foot == 0 ? "Footstep - Left" : "Footstep - Right"); soundObject.transform.position = origin ? origin.position : transform.position; var source = soundObject.AddComponent(); source.clip = selected; source.volume = volume; source.spatialBlend = 1f; source.dopplerLevel = 0f; source.rolloffMode = AudioRolloffMode.Logarithmic; source.minDistance = minDistance; source.maxDistance = Mathf.Max(minDistance, maxDistance); source.Play(); // Leave the sound at the contact location as the foot moves away. Destroy(soundObject, selected.length + 0.1f); } } }