Hello.
Here I have a script that makes the audio fade-in when starting the game.
(All scripts are in C#):
using UnityEngine;
[RequireComponent(typeof(AudioSource))]
public class EasyFadeIn : MonoBehaviour
{
[SerializeField]
private int m_FadeInTime = 10;
private AudioSource m_AudioSource;
private void Awake()
{
m_AudioSource = GetComponent<AudioSource>();
}
private void Update()
{
if (m_AudioSource.volume < 1)
{
m_AudioSource.volume = m_AudioSource.volume + (Time.deltaTime / (m_FadeInTime + 1));
}
else
{
Destroy(this);
}
}
}
I used the same script to make it fade-out by changing the ‘+’ to a ‘-’ and some other minor changes. It works great when I set the volume in the AudioSource to 0.
using UnityEngine;
[RequireComponent(typeof(AudioSource))]
public class EasyFadeOut : MonoBehaviour
{
[SerializeField]
private int m_FadeInTime = 10;
private AudioSource m_AudioSource;
private void Awake()
{
m_AudioSource = GetComponent<AudioSource>();
}
private void Update()
{
if (m_AudioSource.volume > 0)
{
m_AudioSource.volume = m_AudioSource.volume - (Time.deltaTime / (m_FadeInTime - 1));
}
else
{
Destroy(this);
}
}
}
Now, what i want is the audio fade-out script to start playing after Coroutine “waiter” has been started in the following script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine.SceneManagement;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class MenuControl : MonoBehaviour
{
private EasyFadeOut EasyFadeOut;
private EasyFadeIn EasyFadeIn;
private int FadeInTime = 10;
private Delete Delete;
public AudioSource audioSource;
public Image black;
public RawImage black2;
public Animator anim;
public Animator anim2;
public Animator anim3;
public void ButtonStart()
{
StartCoroutine(Fading());
Delete = GetComponent<Delete>();
EasyFadeOut = GetComponent<EasyFadeOut>();
EasyFadeIn = GetComponent<EasyFadeIn>();
}
public void ButtonQuit()
{
Application.Quit();
}
IEnumerator Fading()
{
anim.SetBool("Fade", true);
yield return new WaitUntil(() => black.color.a == 1);
GameObject[] gos = GameObject.FindGameObjectsWithTag("TestTag");
anim2.SetBool("Fadein", true);
foreach (GameObject go in gos)
Destroy(go);
anim3.SetBool("TextFadein", true);
StartCoroutine(waiter());
}
IEnumerator waiter()
{
if (audioSource.volume > 0)
{
audioSource.volume = audioSource.volume - (Time.deltaTime / (FadeInTime - 1));
}
yield return new WaitForSeconds(10);
anim2.SetBool("Fadeout", true);
yield return new WaitUntil(() => black2.color.a == 1);
if (audioSource.volume == 0)
{
SceneManager.LoadScene(1);
}
}
}
But sadly, it only works for a split second before it stops. It changes to volume from 1 to 0.998 (or something similiar) before it stops working.
How do I make it so it continues playing until the volume has reached 0?
I hope you understood my question, as English is not my native language, and I am still learning.
Thank you in advance.