- Home /
music when close to something
Hello,
I have made a little game in unity and i want to know something: i want to know how to make it so that my fps controller can only hear the music if he is close to something, how do it do this?
Answer by TSI25 · Oct 19, 2017 at 07:29 PM
well if you have a reference to the transform of the player, and the transform of the thing they need to get close to you can use a line like
Vector3.Distance(playerTransform.position, thingTransform.position);
and that will give you the distance as a float between those 2 objects. then you can say something like
AudioSource source;
float maxDistance = 5f;
private void SetMusicVolume(float distance)
{
distance = Mathf.Clamp(distance, 0f, maxDistance);
source.volume = Mathf.lerp(1f, 0f, distance/maxDistance);
}
in order to set the volume based on that distance. then you would just have to call that function however often in order to make it actually reactive to the player distance. I would try not to just call it from update since that would get expensive if you had a bunch of these, but using update would probably be the fastest way to make it work.
Your answer
![](https://koobas.hobune.stream/wayback/20220612141415im_/https://answers.unity.com/themes/thub/images/avi.jpg)