Question by
Adrian-Salarda · Jun 09, 2016 at 05:42 AM ·
transformaudioaudiosourceproximity
How to turn off an audio source when another is being played based on proximity?
Hi guys, I'm currently stuck on making a script that allows an audio source to be turned off when another is being played.
The second audio source is played based on its proximity with the player. Here's my c# script so far.
using UnityEngine; using System.Collections;
public class PlaySounds : MonoBehaviour {
private float maxDistance = 20.0f;
private Transform listenerObject;
private bool oldState = false;
public float distance;
public bool outOfRange;
void Start () {
AudioListener listener = FindObjectOfType (typeof(AudioListener));
listenerObject = listener.transform;
}
void Update () {
distance = listenerObject.position - transform.position;
outOfRange = distance.sqrMagnitude > maxDistance * maxDistance;
if (oldState != outOfRange) {
if (outOfRange) {
GetComponent<AudioSource>().Stop ();
} else {
GetComponent<AudioSource>().Play ();
}
}
oldState = outOfRange;
}
}
Comment