Dynamic unloading of audio source based on proximity

My question comes because im exceding the limit of 32 voices and I would like to know if there is an easy way of loading and unloading the voices based on distance.

ive seen a post that seems to seems to take of the loading part, but know I need to figure out how I can stop playback if outside a range

Thank you very much for your time and help

  • Create an empty gameobject (GameObject → Create Empty), name it “Audio Trigger Zone”.
  • Add a Sphere Collider component. (Component → Physics → Sphere Collider)
  • Adjust the radius of the Sphere Collider so that its size covers the area where you’d like the sound trigger to start.
  • Check the “is Trigger” box on the collider settings, in the inspector panel.
  • Add an AudioSource component. (Component → Audio → AudioSource) Make sure “Play On Awake” and “Loop” are not checked.
  • Assign your sound clip to the Audio Source Clip property.
  • Create a new Javascript, and call it “TriggerAudio”. Paste the following into it:

Code:

function OnTriggerEnter() {
    audio.Play();
}
  • Place a copy of this script on to your Audio Trigger Zone gameobject. You should find now that any character or object with a rigidbody entering this zone will cause the audio to trigger.

Well each audio source would have to check the distance to the listener. The listener is usually the maincamera, but you can find it simply with FindObjectOfType.

var maxDistance : float = 20.0f; // in units
private var listenerObject : Transform;
private var oldState = false;

function Start()
{
    var listener : AudioListener = FindObjectOfType(AudioListener);
    listenerObject = listener.transform;
}

function Update()
{
    var distance = listenerObject.position - transform.position;
    var outOfRange = distance.sqrMagnitude > maxDistance*maxDistance;
    if (oldState != outOfRange) // detect a change
    {
        if (outOfRange)
        {
            audio.Stop();
        }
        else
        {
            audio.Play();
        }
    }
    oldState = outOfRange;
}

This script will automatically stop the audio when the listener is out of range and plays it when it comes in range.

ps: Not tested code. I usually use C#, so forgive me any syntax errors :wink: