作者:Daniel Rodríguez
为了解决同样一个基本的问题,我们经常将简单的代码写了一遍又一遍,比如在Unity3D中播放音频就是这种情况。
你需要音频组件:AudioSource和AudioListener,问题是音频片段是通过AudioClip展现,每个AudioSource在某一刻只能有单个AudioClip在播放,有时这已经足够,但有时我们需要让游戏对象能播放多种不同的声音,或许是在同一刻(想象一下,角色说话的同时传出脚步声)。
在你的场景中使用一个管理对象(manager object)采用单件模式是非常自然的方式,我写了一个组件可以关联到manager中。该组件可以在游戏里播放任何声音,代码非常简单并且里面包含了具体的解释。
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
|
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Audio Manager.
//
// This code is release under the MIT licence. It is provided as-is and without any warranty.
//
// Developed by Daniel Rodríguez (Seth Illgard) in April 2010
// http://www.silentkraken.com
//
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
using
UnityEngine;
using
System.Collections;
public
class
AudioManager : MonoBehaviour
{
public
AudioSource Play(AudioClip clip, Transform emitter)
{
return
Play(clip, emitter, 1f, 1f);
}
public
AudioSource Play(AudioClip clip, Transform emitter,
float
volume)
{
return
Play(clip, emitter, volume, 1f);
}
///
/// Plays a sound by creating an empty game object with an AudioSource
/// and attaching it to the given transform (so it moves with the transform). Destroys it after it finished playing.
///
///
///
///
///
///
public
AudioSource Play(AudioClip clip, Transform emitter,
float
volume,
float
pitch)
{
//Create an empty game object
GameObject go =
new
GameObject (
"Audio: "
+ clip.name);
go.transform.position = emitter.position;
go.transform.parent = emitter;
//Create the source
AudioSource source = go.AddComponent
source.clip = clip;
source.volume = volume;
source.pitch = pitch;
source.Play ();
Destroy (go, clip.length);
return
source;
}
public
AudioSource Play(AudioClip clip, Vector3 point)
{
return
Play(clip, point, 1f, 1f);
}
public
AudioSource Play(AudioClip clip, Vector3 point,
float
volume)
{
return
Play(clip, point, volume, 1f);
}
///
/// Plays a sound at the given point in space by creating an empty game object with an AudioSource
/// in that place and destroys it after it finished playing.
///
///
///
///
///
///
public
AudioSource Play(AudioClip clip, Vector3 point,
float
volume,
float
pitch)
{
//Create an empty game object
GameObject go =
new
GameObject(
"Audio: "
+ clip.name);
go.transform.position = point;
//Create the source
AudioSource source = go.AddComponent
source.clip = clip;
source.volume = volume;
source.pitch = pitch;
source.Play();
Destroy(go, clip.length);
return
source;
}
}
|
如您所见,该类有6个Play重载函数,我们有两种类型:一个是transform(emitter),另外一个是Vector3,不同点是如果你提供了一个点(Vector3),声音将在此播放,如果你提供了emitter,声音将在emitter处播放,并且跟随emitter的移动(如开过的汽车)。
希望你觉得它有用!