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 }

 

转载于:https://www.cnblogs.com/VRGamer-006/p/8563714.html

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值