- Home /
Quadruple audio fade script not working completely. Shocker.
I am trying to make a script that plays a song while you are inside a box, and reverts back to the original once you leave. To spice it up, I added fadeouts. Here is the script:
var track1 : AudioClip;
var track2 : AudioClip;
audio.clip = track1;
audio.Play();
var audio1Volume : float = 1.0;
var audio2Volume : float = 0.0;
var track1Playing : boolean = true;
var track2Playing : boolean = false;
var cango : boolean = false;
var didgo : boolean = false;
function OnTriggerEnter(hit : Collider){
cango = true;
Update();
}
function OnTriggerExit(hit : Collider){
didgo = true;
Update2();
}
function Update() {
if (cango == true) {
fadeOut();
if (audio1Volume <= 0.1) {
if(track2Playing == false)
{
track2Playing = true;
track1Playing = false;
audio.clip = track2;
audio.Play();
}
fadeIn();
}
}
}
function Update2() {
if (didgo == true){
fadeOut2();
if (audio1Volume <= 0.1) {
if(track1Playing == false)
{
track1Playing = true;
track2Playing = false;
audio.clip = track1;
audio.Play();
}
fadeIn2();
}
}
}
function fadeIn() {
if (audio2Volume < 1) {
audio2Volume += 0.6 * Time.deltaTime;
audio.volume = audio2Volume;
}
}
function fadeIn2() {
if (audio1Volume < 1) {
audio1Volume += 0.6 * Time.deltaTime;
audio.volume = audio1Volume;
}
}
function fadeOut() {
if(audio1Volume > 0.1)
{
audio1Volume -= 0.6 * Time.deltaTime;
audio.volume = audio1Volume;
if(audio1Volume <= 0.1){
audio.clip = track1;
audio.Stop();
}
}
}
function fadeOut2() {
if(audio2Volume > 0.1)
{
audio2Volume -= 0.6 * Time.deltaTime;
audio.volume = audio2Volume;
if(audio2Volume >= 0.1){
audio.clip = track2;
audio.Stop();
}
}
}
I get no errors or feedback at all, instead, I get annoyed. It works fine at first; it fades out audio1 and fades in audio 2. But the reverse effect does not work. When you leave, it stops the second track, and if you enter again, it plays it very quietly. Track 1 never returns, from what I can tell, anyways.
I was hoping someone could give me a fresh set of professional eyes to see what I might have done wrong. Thanks.
Don't name your functions Update(). Doing so will make them be called as part of Unity's game loop. If that's what you intended, then you shouldn't be calling Update manually from OnTriggerEnter.
Also, your code has an awful lot of duplication. I recommend you not only rename Update/2() and fadeout/2() but also refactor them to be parameterised functions.
Your answer
![](https://koobas.hobune.stream/wayback/20220611234153im_/https://answers.unity.com/themes/thub/images/avi.jpg)