Is there a way to change AudioSource’s Roll-off values by scripting?
I have a gameobject, which can be used either by me or someone else. The gameobject holds an audiosource and a piece of code, which controls the audiosource. I would like to keep the volume itself static, but by changing the values of Roll-Off (for example ON/OFF) I could disable the object’s roll-off while holding the object, and enable it when someone else is holding on to it. This way I wouldn’t hear the other player when he’s miles away, while not having annoying problems with roll-off myself. Because of the 3rd person view and camera angles I would prefer to be able to disable the roll-off rather than setting it “close enough”.
I hope this short introductory was enough to explain my situation. If you have any suggestions, let me know.
This is a very lacking part of your audio api. One of the many reasons why this engine is difficult to use out of the box for professional use. I cant believe this is still true 5 years later. If you have a game with 100’s or thousands of sounds you have to create your own solution to give each sound it own 3D sound settings.
Not that hard to do. Why can’t you guys get this done?
FlightOfOne’s reply was also what I was after, but I still wanted that nice logarithmic dropoff. I modified it with an equation that gives that logarithmic dropoff. I ended up not needing it however, as I realized I could make an audiosource prefab and pass that into the script (The design really isn’t ideal but I stuck with it). Anyways, it has an issue where the tangents aren’t smoothed out so the graph doesn’t curve nicely. It should be resolvable by looping through the keyframes and using the SmoothTangents() function to make it a nice curve. I hope this is able to help someone!
public void setAudioProperties()
{
int minDistance = 1;
int maxDistance = 5;
// Spatial blend will give audio a 3D presence
unityAudioSource.spatialBlend = 1;
unityAudioSource.minDistance = minDistance;
unityAudioSource.maxDistance = maxDistance;
// The curve will make the audio drop to 0 if a user is too far.
// We want to make the curve logarithmic as to simulate real world drop off.
// We make the base of the log maxDistance so it 0's out naturally at max distance
Keyframe[] keyframes = new Keyframe[maxDistance - minDistance];
for(int i = 0; i < maxDistance - minDistance; i++)
{
int distanceFromSource = i + minDistance;
// Multiplying by maxDistance ensures that the logarithm doesn't decrease too quickly for varied distance
// The second keyframe entry is the volume. It starts at 1, and decreases logarithmically
keyframes[i] = new Keyframe(distanceFromSource, 1 - Mathf.Log(i + 1, maxDistance));
}
AnimationCurve distanceCurve = new AnimationCurve(keyframes);
unityAudioSource.rolloffMode = AudioRolloffMode.Custom;
unityAudioSource.SetCustomCurve(AudioSourceCurveType.CustomRolloff, distanceCurve);
}