大家好
最近在unity 上遇到一個問題
如何淡出淡入音樂?
找一找還真發現很簡單就可實現
//淡入淡出音樂
public static IEnumerator FadeMusic(AudioSource audioSource, float duration, float targetVolume)
{
float currentTime = 0;
float start = audioSource.volume;
while (currentTime < duration)
{
currentTime += Time.deltaTime;
audioSource.volume = Mathf.Lerp(start, targetVolume, currentTime / duration);
yield return null;
}
yield break;
}
//再用這個呼叫即可
audioSource.volume = 0;//如果要從小聲到大聲.可以先將音量設定成0
StartCoroutine(FadeMusic(audioSource, 持續幾秒, 音量目標0到1));
就是要活用 StartCoroutine 這個功能
就可以用 while 迴圈方便寫很多時間性質的功能需求
不用都寫在 update 裡面
給大家參考囉

留言板
歡迎留下建議與分享!希望一起交流!感恩!