[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 }
时间若流水,恍惚间逝去
原文地址:https://www.cnblogs.com/alanshreck/p/13627932.html