Cabbage Logo
Back to Cabbage Site

Unity/Cabbage: Gain being controlled by distance from Object

I have an object in Unity with a Cabbage Instrument attached. How do I control the volume of that sound relative to the distance to/from it? Am I right in thinking that the volume is not affected by the usual Audio Source Max/Min distance.

So far I have been using Vector3.Distance to calculate the distance between me and the object but Im not getting proper results to be fed to the Gain in Cabbage. Anyone any ideas? Cheers

Actually, it works the same, because CsoundUnity is essentially an AudioSource. I just tried it here and it works without any problems. I setup a cube to be a CsoundUnity object, and placed a sphere that has an AudioListener attached. As I move the two closer together I hear both doppler and volume changes. Don’t forget to set the Spatial Blend settings to 3D.

This should also work. For example:

    public Transform soundingObject;
    void Example() {
        if (other) {
            float dist = Vector3.Distance(other.position, transform.position);
            csoundUnity.setChannel("gain", dist);
        }
    }  

And you might have something like this in your Csound code:

instr 1
aOut oscili chnget:k("gain"), 400
outs aOut, aOut 
endin

You’ll probably need to scale the distance value so that it’s between 0 and 1. And you should probably use an exponential scaling factor so that it behaves somewhat like it would in the real world.

Hope this helps.

Great thanks, the first option seems the simplest so I will go with that.