Setting FX mixer volume by speed of a Rigidbody?

I’ve been trying to set FX volume in the main mixer by the speed of a Rigidbody. Below is code to affect a slider, (which is hidden offscreen) as I thought that might be simple, but no good it seems. And yes there is another FX slider in the in-game menu, (which works OK) so maybe that’s part of the problem.

I’ve no particular desire to use a slider, I just want the levels of all FX to drop/ raise according to the cube’s speed.

GameController.cubeSpeed is the speed variable and cubeVol does work out at somewhere between 0 and 1; that seems OK. But what parameter should go into MoveSlider() ?? I put 0.1f in and it saw no effect on the FX mixer; no errors in the console either.

I hope there’s a better way?

    public AudioMixer mainMixer;
    public Slider fxSlider;
    public float cubeVol;

    void Start ()
    {
        audioSource  = GetComponent<AudioSource> ();   
    }

    public void MoveSlider (float cubeVol) {
        fxSlider.value = cubeVol;    
    }

    void Update (){
        cubeVol= GameController.cubeSpeed / 100;
        MoveSlider( what? );
    }

Just remove the function and move the code that sets the value into the Update() function.

public AudioMixer mainMixer;
public Slider fxSlider;
public float cubeVol;

void Start ()
{
    audioSource  = GetComponent<AudioSource> ();
}

void Update (){
    cubeVol= GameController.cubeSpeed / 100;
    fxSlider.value = cubeVol;
}

That’s because the code is perfectly fine as far as the compiler is concerned. It’s more of a logic error than anything and the compiler is not capable of understanding that’s the case. Basically it’s a problem with variable scope. I recommend the following reading but I’ll try to explain it below.

https://tutorialstown.com/csharp-variable-scopes/

In your old code you have a variable declared in the class:

public float cubeVol;

But by declaring a variable of the same name in the function parameter you were overriding the class variable:

public void MoveSlider (float cubeVol) {
    fxSlider.value = cubeVol;
}

Because of that the value you were setting in Update() was literally being ignored:

void Update (){
    cubeVol= GameController.cubeSpeed / 100;
    MoveSlider( what? );
}
1 Like

Thanks for answering so quickly Ryiah. :slight_smile: I was just blind to line 3, I was too busy looking below it. Glad to see it was simpler than I thought.

It does lock up the audio slider in the in-game menu though: can’t drag it now, but I expected that; I can sort it out.

The slider value actually has to be between -80 and 0, so my final formula is simply
cubeVol = GameController.cubeSpeed - 25;
because below -25 my imported audio files are silent.