赞
踩
音频文件导入到Unity以后,音频文件会变成audioClip。即音频片段。
Unity播放声音的组件,关联了AudioClip就可以播放声音了。具体的参数参考官方文档。
每个场景只能有一个AudioListener组件。它的声音播放必需的组件。默认绑在MainCamera上。
1、在Cube上添加一个AudioSource。设置对应的参数,即可以播放背景音乐。
1、新建一个Slider用于控制音量,新建一个Toggle按钮,用于控制音乐是否播放。
2、新建一个脚本BackSoundControl.cs挂载在MainCamera上。
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.UI;
-
- public class BackSoundControl : MonoBehaviour
- {
- public Slider slider;
- public Toggle toggle;
- public AudioSource soundPlay;
-
- public void PlayOrStop()
- {
- if (toggle.isOn)
- {
- soundPlay.gameObject.SetActive(true);
- Volume();
- }
- else
- {
- soundPlay.gameObject.SetActive(false);
- }
- }
-
- public void Volume()
- {
- soundPlay.volume = slider.value;
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreBlack.png)
3、相应参数的设置
4、Toggle和Slider的绑定设置
这样就可以了。
1、新建一个球体预制体,比较简单哈
2、新建三个Cube。记住每个Cube上都要有Collider。不然射线检测不能用
3、新建一个脚本SoundDemo.cs。挂在在MainCamera上。
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
-
- public class SoundDemo : MonoBehaviour
- {
- public GameObject perfab;
-
- // Start is called before the first frame update
- void Start()
- {
-
- }
-
- // Update is called once per frame
- void Update()
- {
- if(Input.GetMouseButtonDown(0))
- {
- Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
- RaycastHit hit;
- if(Physics.Raycast(ray,out hit))
- {
- Instantiate(perfab, hit.transform.position, Quaternion.identity);
- }
- }
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreBlack.png)
4、到这里我们可以实现的效果
5、我们新建一个脚本EffectSoundControl.cs声音的控制。
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
-
- [RequireComponent(typeof(AudioSource))]
-
- public class EffectSoundControl : MonoBehaviour
- {
- public AudioClip[] audioClips;
- private AudioSource audioSource;
-
- private void Start()
- {
- audioSource = GetComponent<AudioSource>();
- audioSource.PlayOneShot(audioClips[0]);
- }
-
- private void OnBecameInvisible() //当游戏对象离开视野的时候运行
- {
- audioSource.PlayOneShot(audioClips[1]);
- Destroy(gameObject,2f);
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreBlack.png)
6、我们把上面的这个脚本挂载在Sphere预制体上,并设置相应的参数
7、至此我们实现了点击方块,会播放一个声音,生成一个球,球会自由下落,当球消失在视野中,会播放另外一种声音,2秒后销毁球体。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。