Unity 如何动态改变场景BGM(渐出渐入)

您所在的位置:网站首页 ppt渐入渐出怎么设置 Unity 如何动态改变场景BGM(渐出渐入)

Unity 如何动态改变场景BGM(渐出渐入)

2024-07-17 19:41| 来源: 网络整理| 查看: 265

我希望角色在完成某个条件后将会改变场景BGM,并且拥有渐出渐入的效果(当前BGM音量逐渐减小至消失,随后目标BGM音量逐渐增大到目标值)

首先,我们应添加不同AudioSource,并为他们绑定上所需BGM。为了方便管理,我们把当前场景要用到的BGM放到同一游戏对象里(此例为SceneSound/BGM)

接着,我们要明白这个条件是什么,最常见的可能就是玩家到达某一地点

以此为例,此时我们需要的是一个触发器(不展示过程)

最后,我们需要为触发器所在的物体添加一个脚本以帮助我们切换BGM,代码如下:

using System.Collections; using System.Collections.Generic; using UnityEngine; public class BGMSwitch : MonoBehaviour { public AudioSource goalBgm; public float goalVolume; void OnTriggerEnter2D(Collider2D other) { if (other.tag != "Player") return; GameObject BGM = GameObject.Find("SceneSound/BGM"); foreach (Transform child in BGM.transform) { AudioSource source = child.GetComponent(); if (source != goalBgm && source.enabled == true) {Debug.Log(source); StartCoroutine(Weak(source));} if (source == goalBgm) {goalBgm.enabled = true;} } } IEnumerator Weak(AudioSource bgm) { while (bgm.volume > 0.02f) { bgm.volume -= 0.01f; yield return new WaitForSeconds(0.1f); } bgm.enabled = false; StartCoroutine(Enhance(goalBgm, goalVolume)); //其他BGM声音消失后开始增强目标BGM } IEnumerator Enhance(AudioSource goalBgm, float goalVolume) { while (goalBgm.volume < goalVolume) { goalBgm.volume += 0.01f; yield return new WaitForSeconds(0.01f); } } }

主要过程为:

1.foreach逐个查询BGM中所有的子物体

如果该子物体不是目标且为激活状态,则执行迭代器Weak以逐渐减弱音量

如果该子物体是目标,则将其变为激活状态

2.当前BGM音量降低为0后,执行迭代器Enhance以逐渐增加目标BGM音量



【本文地址】


今日新闻


推荐新闻


    CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3