UF_OLDL8——音效管理模块

音效管理模块

在游戏里,各个对象可能都会有各种音效,很明显,为每个对象都单独添加音效源难以统一管理的

我们需要写一个独立的音效管理模块来统一管理它们

通过这个模块,使得游戏对象不再需要自己控制音效源,只需要调用该模块即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

public class MusicManager : BaseManager<MusicManager>
{
//唯一的背景音乐组件
private AudioSource bkMusic = null;
//音乐大小
private float bkValue = 1;

//音效依附对象
private GameObject soundObj = null;
//音效列表
private List<AudioSource> soundList = new List<AudioSource>();
//音效大小
private float soundValue = 1;


public MusicManager()
{
MonoManager.Instance().AddUpdateListener(Update);
}

private void Update()
{
for (int i = soundList.Count - 1; i >= 0; i--)
{
if (soundList[i].isPlaying)
{
GameObject.Destroy(soundList[i]);
soundList.RemoveAt(i);
}
}
}

/// <summary>
/// 播放背景音乐
/// </summary>
/// <param name="name"></param>
public void PlayBKMusic(string name)
{
if (bkMusic == null)
{
GameObject obj = new GameObject(name);
obj.name = "BkMusic";
bkMusic = obj.AddComponent<AudioSource>();
}
//异步加载背景音乐,加载完成后播放
ResourcesManager.Instance().LoadAsync<AudioClip>("Music/BK/" + name, (audioClip) =>
{
bkMusic.clip = audioClip;
bkMusic.volume = bkValue;
bkMusic.Play();
});
}

/// <summary>
/// 改变背景音乐 音量大小
/// </summary>
/// <param name="value"></param>
public void ChangeBKValue(float value)
{
bkValue = value;
if (bkMusic == null) return;
bkMusic.volume = bkValue;
}

/// <summary>
/// 暂停背景音乐
/// </summary>
public void PauseBKMusic()
{
if (bkMusic == null) return;
bkMusic.Pause();
}

/// <summary>
/// 停止背景音乐
/// </summary>
public void StopBKMusic()
{
if (bkMusic == null) return;
bkMusic.Stop();
}

/// <summary>
/// 播放音效
/// </summary>
public void PlaySound(string name, bool isLoop, UnityAction<AudioSource> callBack = null)
{
if (soundObj == null)
{
soundObj = new GameObject();
soundObj.name = "Sound";
}
//当音效资源异步加载结束后 再添加一个音效
ResourcesManager.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);
if (callBack != null)
callBack(source);
});
}

/// <summary>
/// 改变音效声音大小
/// </summary>
/// <param name="value"></param>
public void ChangeSoundValue(float value)
{
soundValue = value;
for (int i = 0; i < soundList.Count; ++i)
soundList[i].volume = value;
}

/// <summary>
/// 停止音效
/// </summary>
public void StopSound(AudioSource source)
{
if (soundList.Contains(source))
{
soundList.Remove(source);
source.Stop();
GameObject.Destroy(source);
}
}
}