Hi,
i already read a few posts about lerping AudioListener to create a global fading of audio.
I have a strange and annoying problem:
void Update()
{
AudioListener.volume = Mathf.Lerp (AudioListener.volume, 0f, Time.deltaTime);
}
This works just fine, but it fades out immediately of course, and that is not what i want.
So i declare a float to be 0 at a certain condition and just replace the 2nd argument in Mathf.Lerp with that float. Because that is how it works. But it doesn’t work. I get this exact code to work with AudioSources.
This is what i have in my script:
void Update()
{
if (Input.GetKeyDown(KeyCode.Q)) // Of course this works! Nothing fancy.
{
volume2 = 0f;
}
AudioListener.volume = Mathf.Lerp (AudioListener.volume, volume2, 2*Time.deltaTime);
}
I test it, and volume2 becomes 0 just as intended but the volume doesn’t fade to zero.
It doesn’t change at all.
I also saw that other people posted this kind of code for AudioListener.volume
But it doesn’t work. Why does it just work when i don’t use any variables??
Maybe it’s an obvious problem, i just sat infront of my pc for 10 hours creating models, code and textures, so forgive me if i don’t get it at the moment.
Please enlighten me. ^^
Thanks.
Might be overkill for your usecase, but:
bool fading;
const float totalFadeTime = 1000f;
float currentFadeTime;
float startVolume;
void Update()
{
if (!fading && Input.GetKeyDown(KeyCode.Q))
{
fading = true;
startVolume = AudioListener.volume;
}
if (fading)
{
currentFadeTime += Time.deltaTime;
if(currentFadeTime > totalFadeTime)
{
fading = false;
currentFadeTime = totalFadeTime;
}
AudioListener.volume = Mathf.Lerp (startVolume, 0, currentFadeTime/totalFadeTime);
}
Hi, thank you guys for your answers and solutions.
I took a nap shortly after writing this question and after a cup of coffee, I thought about how I could find a way to make it work.
I simply created a new script with this:
PS: Yes you can call a boolean “BOOL”. 
public class Test : MonoBehaviour {
public bool BOOL;
public float FLOAT1, FLOAT2, FLOAT3;
// Use this for initialization
void Start () {
BOOL = false;
}
// Update is called once per frame
void Update () {
if(Input.GetKeyDown(KeyCode.Q))
{
FLOAT2 = 0f;
BOOL = true;
}
if(Input.GetKeyDown(KeyCode.E))
{
FLOAT2 = 1f;
}
AudioListener.volume = Mathf.Lerp (AudioListener.volume, FLOAT2, Time.deltaTime);
FLOAT3 = AudioListener.volume;
}
}
As you can see, I don’t make use of the boolean in this example, since it is a simple test.
For now, if I press Q or E, the volume smoothly fades between 0f and 1f!
I assume there was an issue with the float volume2
that i had declared in the “problem”-code.
I have to re-read the class where I had encountered the problem.
Maybe I have two conditions setting volume2
to different values and so it couldn’t change.
But for now I can confirm that Mathf.Lerp(a,b,t)
works as intended with AudioListener.volume
!
Thank you for taking time to read this!