Audio Fading too fast

I dont know what’s worng with my script but I know where its happening, if anyone can help me out I would be very thankful. I know its happening on the “volume -= 0.01 * Time.time;” line but I don’t know what to change, as soon as my “TopCameraCollision” hits the trigger, the float value drops very fast so it’s like the music doesn’t even fade it just stops. Here is my script:

#pragma strict

private var music : AudioSource;
private var mainCamera : GameObject;
var volume : float;

function Start()
{
	mainCamera = GameObject.FindWithTag("MainCamera");
	music = mainCamera.GetComponent(AudioSource);
	music.enabled = true;
	music.volume = 0.5;
}

function OnTriggerEnter(collider : Collider )
{
	if(collider.gameObject.name == "TopCameraCollision")
	{
		Debug.Log("Hit1");
		if(music.volume > 0)
		{
			Debug.Log("Hit2");
			volume -= 0.01 * Time.time;
			music.volume = volume;
		}
		else if(music.volume <= 0)
		{
			Debug.Log("Hit3");
			volume = 0;
			music.volume = volume;
		}
	}
}

You are using Time.time which is the time since the game began - so you should probably be using Time.deltaTime which is the time of the current frame.

Now the next problem is that you are only doing this when you enter the trigger and only once. So if you switch to Time.deltaTime you will have to enter the trigger multiple times to get the volume to fade. If that’s not the effect you are looking for you probably want to consider a coroutine.

  if(music.volume > 0)
  {
       StartCoroutine(FadeMusic(2));
  }

  ...

  function FadeMusic(seconds : float)
  {
      var initialVolume = volume;
      var t = 0;
      while(t < 1)
      {
          t += Time.deltaTime/seconds;
          volume = Mathf.Lerp(initialVolume, 0, t);
          music.volume = volume;
          yield null;
      }
  }

I had the same issue, so I modified whydoidoit’s code to solve the problem. The issue had been that the variable ‘volume’ was never initialized, and t was not initiaized as a float. I removed volume and just directly used music.volume.

#pragma strict

private var music : AudioSource;
private var mainCamera : GameObject;
 
function Start()
{
	mainCamera = GameObject.FindWithTag("MainCamera");
	music = mainCamera.GetComponent(AudioSource);
	music.enabled = true;
	music.volume = 1.0;
}


function FadeOut(seconds : float)
{
	var initialVolume:float = music.volume;
	var t=0.0f;
	while(t < 1.0)
	{
		Debug.Log(""+t);
		t += Time.deltaTime/seconds;
		music.volume = Mathf.Lerp(initialVolume, 0, t);
		yield ;
	}
}