HI, I want a song on an object to increase in volume as my player gets closer the the object without the song changing from left to right speakers when the player changes directions. I simply want the volume to increase as the player gets closer, but how do I do that?
The 3D sound makes the music change speakers according to the direction of my player and if its not a 3D sound its the same volume regardless.
Here’s a quick example. Of course you have to adapt the scaling to work to your preferences (the one in the script is just to make a point).
using UnityEngine;
using System.Collections;
public class ScaleVolume : MonoBehaviour {
public GameObject Player;
AudioSource Music;
// Use this for initialization
void Start () {
Music = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update () {
float distance = Vector3.Distance (transform.position, Player.transform.position);
if(distance < 10) {
Music.volume = 1 - (distance / 10);
} else {
Music.volume = 0;
}
}
}
Here’s a more optimized version of the script @michaelhartung posted:
using UnityEngine;
using System.Collections;
public class ScaleVolume : MonoBehaviour {
// Don't make settings public unless it's absolutely necessarry
[SerializeField]
private Transform reference;
// Cache our own transform
private Transform transform;
private AudioSource audioSource;
// Use Awake() instead of Start() because you're initializing the GameObject's own, private fields
private void Awake() {
transform = GetComponent<Transform>();
audioSource = GetComponent<AudioSource>();
}
private void Update () {
// Use the squared distance instead of the distance because it's much faster and we don't need the exact value in this case
float sqrDistance = (reference.position - transform.position).sqrMagnitude;
// Compare with 10² instead of 10 because we're comparing to distance²
if(sqrDistance < 100.0f) {
audioSource.volume = 1.0f - (distance / 1.0f);
} else {
audioSource.volume = 0.0f;
}
}
}