MusicManager.cs📄
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
/// <summary>
/// 1.Input类
/// 2.事件中心模块
/// 3.公共Mono模块的使用
///
/// 设计理念
/// 1.创建场景当中的两个对象,一个为背景音乐和音效
/// 2.音效的播放使用实例化音效且作为附件方式
/// </summary>
public class MusicManager : Singleton<MusicManager>
{
//背景音乐
private AudioSource bkMusic = null;
private float bkValue = 0.5f;
//音效的播放对象
private GameObject soundObj = null;
private List<AudioSource> soundList = new List<AudioSource>();
private float soundValue = 0.5f;
//执行一次,放在场景当中的单一对象来实现检查或者更新方法
public MusicManager()
{
MonoManager.Instance.AddUpdateListner(Update);
}
//该方法是更新和检查的方法
private void Update()
{
for (int i = 0; i < soundList.Count; i++)
{
if (!soundList[i].isPlaying)
{
GameObject.Destroy(soundList[i]);
soundList.RemoveAt(i);
}
}
}
//播放背景音乐
public void PlayBKMusic(string name)
{
if (bkMusic == null)
{
//创建挂载对象
GameObject go = new GameObject("BKMusic");
//加载资源
ResourceManager.Instance.LoadAsync<AudioClip>("Music/BK/" + name, (clip) =>
{
bkMusic = go.AddComponent<AudioSource>();
bkMusic.clip = clip;
bkMusic.loop = true;
bkMusic.volume = bkValue;
bkMusic.Play();
});
}
else
{
bkMusic.Play();
}
}
//停止背景音乐
public void StopBKMusic()
{
if (bkMusic == null)
{
return;
}
bkMusic.Stop();
}
//暂停背景音乐
public void PauseBKMusic()
{
if (bkMusic == null)
{
return;
}
bkMusic.Pause();
}
//提供改变改变背景音乐
public void ChangeBKMusic(float value)
{
if (bkMusic == null)
{
return;
}
bkValue = value;
bkMusic.volume = bkValue;
}
//提供播放音效
public void PlaySound(string name,UnityAction<AudioSource> callBack=null,bool isLoop=false)
{
//一般播放音效就不会再播放一次了
if (soundObj==null)
{
soundObj = new GameObject("Sound");
}
ResourceManager.Instance.LoadAsync<AudioClip>("Music/Sound/" + name, (clip) =>
{
AudioSource source = soundObj.AddComponent<AudioSource>();
source.clip = clip;
source.loop = isLoop;
source.volume = soundValue;
source.Play();
soundList.Add(source);
callBack?.Invoke(source);
});
}
//停止音效音乐
public void StopSound(AudioSource source)
{
if (soundList == null)
{
return;
}
if (soundList.Contains(source))
{
soundList.Remove(source);
source.Stop();
GameObject.Destroy(source);
}
}
//
public void PauseSound(AudioSource source)
{
if (soundList == null)
{
return;
}
for (int i = 0; i < soundList.Count; i++)
{
soundList[i].mute = !soundList[i].mute;
}
}
//提供改变改变背景音乐
public void ChangeSound(float value)
{
if (soundList == null)
{
return;
}
soundValue = value;
for (int i = 0; i < soundList.Count; i++)
{
soundList[i].volume = soundValue;
}
}
}