声音系统,管理音效
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SoundManager : SingletonMono<SoundManager>
{
private AudioSource backgroundMusic = null;
private float backgroundValue = 1;
private float soundValue = 1;
private GameObject soundObj = null;
private List<AudioSource> soundList = new List<AudioSource>();
public SoundManager()
{
MonoMgr.GetInstance().AddUpdateListener(SoundUpdate);
}
public void SoundUpdate()
{
for (int i = soundList.Count - 1; i > 0; i--)
{
if (!soundList[i].isPlaying)
{
GameObject.Destroy(soundList[i]);
soundList.RemoveAt(i);
}
}
}
public void PlayBackgroundMusic(string name)
{
if (backgroundMusic == null)
{
GameObject obj = new GameObject("backgroundMusic");
backgroundMusic = obj.AddComponent<AudioSource>();
}
//异步加载背景音乐并且加载完成后播放
ResManager.GetInstance().LoadAysnc<AudioClip>("Music/" + name, (clip) =>
{
backgroundMusic.clip = clip;
backgroundMusic.loop = true;
backgroundMusic.volume = backgroundValue;
backgroundMusic.Play();
}
);
}
public void ChangeBackgroundMusicValue(float v)
{
backgroundValue = v;
if (backgroundMusic == null)
return;
backgroundMusic.volume = backgroundValue;
}
public void PauseBackgroundMusic()
{
if (backgroundMusic == null)
return;
backgroundMusic.Pause();
}
public void StopBackgroundMusic()
{
if (backgroundMusic == null)
return;
backgroundMusic.Stop();
}
public void PlaySound(string name, bool isLoop, Action<AudioSource> callback = null)
{
if (soundObj == null)
{
soundObj = new GameObject();
soundObj.name = "Sounds";
}
AudioSource source = soundObj.AddComponent<AudioSource>();
ResManager.GetInstance().LoadAysnc<AudioClip>("Music/" + name, (clip) =>
{
source.clip = clip;
source.loop = isLoop;
source.volume = soundValue;
source.Play();
//音效异步加载结束后,将这个音效组件加入集合
soundList.Add(source);
if (callback != null)
callback(source);
});
}
public void ChangeSoundValue(float v)
{
soundValue = v;
for (int i = 0; i < soundList.Count; i++)
{
soundList[i].volume = v;
}
}
public void StopSound(AudioSource source)
{
if (soundList.Contains(source))
{
soundList.Remove(source);
source.Stop();
GameObject.Destroy(source);
}
}
}
核心:
1.背景音乐:专门的AudioSource存储bgm,在调用方法后创建声音对象。
2.普通音效:list存储audiosource,在调用后通过update检查是否播放完毕,播放完毕则移除list并销毁。
PlayBackgroundMusic | 播放名字的音乐 |
ChangeBackgroundMusicValue | 修改背景音乐音量 |
PauseBackgroundMusic | 暂停背景音乐 |
StopBackgroundMusic | 停止背景音乐 |
PlaySound | 播放音效 |
ChangeSoundValue | 修改音效的音量 |
StopSound | 停止音效 |
测试:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SoundTest : MonoBehaviour
{
private bool isPlayBackgroundMusic = false;
private bool isPlaySound = false;
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0) && !isPlayBackgroundMusic)
{
isPlayBackgroundMusic = true;
SoundManager.GetInstance().PlayBackgroundMusic("BGM");
}
if (Input.GetMouseButtonDown(0) && !isPlaySound)
{
isPlaySound = true;
SoundManager.GetInstance().PlaySound("BGM", false);
}
}
}