Unity3D实现随机播放背景音频

1.先在第一人称下新建空白物体,命名“audio”

2.在audio中加入Audio Source

3.在第一人称组件里添加Audio Liistener和Audio脚本

4.脚本中添加代码

 1 using UnityEngine;
 2 using System.Collections;
 3 
 4 public class audio : MonoBehaviour {
 5 
 6     public AudioSource audioSource;
 7     public AudioClip otherClip1;
 8     public AudioClip otherClip2;
 9     public AudioClip otherClip3;
10     public float musicVolume;
11     public float randomNum;
12     public int state;
13 
14     // Use this for initialization
15     void Start () {
16         musicVolume = 0.5f;
17         randomPlay();
18     }
19     
20     // Update is called once per frame
21     void Update () {
22         audioSource.volume = musicVolume;
23         if ((state == 1 && !audioSource.isPlaying)||(state == 2 && !audioSource.isPlaying) ||(state == 3 && !audioSource.isPlaying)) { randomPlay(); }
24     }
25 
26     void randomPlay()
27     {
28         randomNum = Random.Range(1.0f, 4.0f);
29         if (randomNum >= 1.0f && randomNum < 2.0f) { state = 1; audioSource.clip = otherClip1; audioSource.Play(); }
30         else if (randomNum >= 2.0f && randomNum < 3.0f) { state = 2; audioSource.clip = otherClip2; audioSource.Play(); }
31         else if (randomNum >= 3.0f && randomNum <= 4.0f) { state = 3; audioSource.clip = otherClip3; audioSource.Play(); }
32     }
33 
34 }

 

posted @ 2018-03-13 23:31  Helix006  阅读(603)  评论(0编辑  收藏  举报