// Play a random ambient sound every so many seconds IEnumerator PlayAmbience(AmbientSound sounds) { AudioSource audioSource = sounds.zone.gameObject.GetComponent <AudioSource>(); // Keep playing while the audio manager exists while (true && sounds.zone != null) { // Play a random sound around the listener SoundEffect randomSound = sounds.GetRandomSound(); audioSource.clip = randomSound.sound; // If the sound is able to be heard if (sounds.zone.source.volume > 0) { // Play the effect audioSource.Play(); // Wait the average time before playing the next sound yield return(new WaitForSeconds( sounds.averageSecondsPerNoise * UnityEngine.Random.Range( Mathf.Max(0, sounds.averageSecondsPerNoise - sounds.randomSecondDeviation), sounds.averageSecondsPerNoise + sounds.randomSecondDeviation) + randomSound.sound.length)); } yield return(new WaitForEndOfFrame()); } }