脚本编写背景音乐
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlaySound : MonoBehaviour
{
//播放器,也就是音频源
private AudioSource player;
//音频剪辑
public AudioClip music;
// Start is called before the first frame update
void Start()
{
//获得该游戏物体身上的音频源
player = GetComponent<AudioSource>();
//或者Resources.Load用来读取Resources文件夹中的文件,泛型中填写读取的类型,参数中填写读取得文件名称
player.clip = music;
//循环
player.loop = true;
//音量
player.volume = 0.5f;
}
// Update is called once per frame
void Update()
{
//空格键控制播放音频
if (Input.GetKeyDown(KeyCode.Space))
{
if (player.isPlaying)
{
player.Pause();
}
else
{
player.Play();
}
}
}
player.Pause();
和player.Stop();
的区别
player.Pause();
是暂停,当开启的时候,接着暂停时的音乐播放。
player.Stop();
是中止,开启的时候,是重新播放音乐。
Resources.Load用来读取Resources
将第18行中的代码player.clip = music;
替换为player.clip=Resources.Load<AudioSource>("音乐名字");
编写特效音乐
用于射击或者打击等音乐
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlaySound : MonoBehaviour
{
//播放器,也就是音频源
private AudioSource player;
//音频剪辑
public AudioClip se;
// Start is called before the first frame update
void Start()
{
//获得该游戏物体身上的音频源
player = GetComponent<AudioSource>();
//或者Resources.Load用来读取Resources文件夹中的文件,泛型中填写读取的类型,参数中填写读取得文件名称
player.clip = se;
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButton(0))
{
player.PlayOneShot(se);
}
}
}