[Unity3D] 通过判断游戏物体对象的ActiveInHierarchy状态切换背景音乐

复制代码
 1 using System.Collections;
 2 using System.Collections.Generic;
 3 using UnityEngine;
 4 
 5 public class ChangeBGM : MonoBehaviour
 6 {
 7     /* 音频组件 */
 8     private AudioSource audioSource;
 9 
10     /* 被判断物体对象,需手动拖入对象 */
11     public GameObject BGStorePanel;
12 
13     /* 音频数组,需手动添加数组长度及音乐*/
14     public AudioClip[] BgmList;
15 
16 
17     void Start()
18     {
19         /* 开始获取音频组件,并播放一个音乐 */
20         audioSource = this.GetComponent<AudioSource>();
21         audioSource.clip = BgmList[0];
22         audioSource.Play();
23     }
24 
25 
26     void Update()
27     {
28 
29         /* 每帧判断是否正在播放 */
30         if (audioSource.isPlaying) {
31             /* 判断游戏物体对象的状态如果是true显示的 */
32             if (BGStorePanel.activeInHierarchy == true) {
33                     /* 将正在播放的音乐暂停 */
34                     audioSource.Pause();
35                     /* 切换音乐 */
36                     audioSource.clip = BgmList[1];
37                     /* 可选参数循环播放 */
38                     audioSource.loop = false;
39                     /* 播放音乐 */
40                     audioSource.Play();
41 
42             }
43         }
44     }
45 }
复制代码

 

posted @   伊凡晴天  阅读(702)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示