来自于:伊凡晴天

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