You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
* The most important functions to control the component are:
38
+
*`.Play()`
39
+
*`.Pause()`
40
+
*`.Stop()`
28
41
```c#
29
-
publicAudioSourceaudio;
42
+
[SerializeField]AudioSourceaudio;
30
43
if (PlayerGrabbedCoin)
31
44
audio.Play();
32
45
if (DoSomethingElse)
@@ -72,6 +85,62 @@ Then, add sounds to your game. Try at least these two kinds of sound effects:
72
85
1) a one-time sound effect that can be triggered with code
73
86
2) looping sound that plays all the time
74
87
75
-
## Playing sound when something gets destroyed
88
+
## Note: Playing sound when something gets destroyed
89
+
90
+
* If you add an audio source to a GameObject that gets destroyed when the sound should be played, the sound stops abruptly
91
+
* Instead, add the audio source to some GameObject that you know won't be destroyed
92
+
* E.g, for playing a sound when collecting a coin, add a CoinPlayer GameObject with an Audiosource component, and call its `.Play()` method when collecting the coin.
93
+
94
+
## Fading between volume levels
95
+
96
+
There are many ways to fade in/out audio. Here, we present an example that needs very minimal code.
97
+
98
+
* Create a new audio mixer asset: *Create > Audio Mixer*.
99
+
* Name it "FadeMixer" or something like that.
100
+

101
+
* Click *Open*
102
+
103
+
---
104
+
105
+

106
+
107
+
* In the Mixer view:
108
+
* Name the existing Snapshot to *VolumeOn*
109
+
* Create a new snapshot *VolumeOff*
110
+
* Set its volume in the *Master* mixer group's slider to -80dB.
111
+
* Right click *VolumeOff* and select *Set as start Snapshot*.
112
+
113
+
---
114
+
115
+
* In project view, expand the mixer asset to see the *Master* mixer group and the two snapshots *VolumeOn* and *VolumeOff*.
116
+
* Drag the *Master* group to the audio source component that you want to fade.
117
+
* Then, in the script where you want to control the fade, create a new variable:
118
+
```c#
119
+
usingUnityEngine.Audio;
120
+
...
121
+
[SerializeField] AudioMixerSnapshotVolumeOn;
122
+
```
123
+
* Drag the *VolumeOn* snapshot to the inspector to the corresponding variable.
124
+
* Then, we can fade from the default *VolumeOff* snapshot to the *VolumeOn* snapshot by calling the method
125
+
```c#
126
+
VolumeOn.TransitionTo(3); // fade takes 3 seconds
127
+
```
128
+
129
+
---
130
+
131
+
<div class="columns" markdown="1">
132
+
<div markdown="1">
133
+
134
+

135
+
136
+
Here's what the audio mixer asset looks like when expanded.
137
+
138
+
</div>
139
+
<div markdown="1">
140
+
141
+

142
+
143
+
Here, the *Master* audio mixer group is dragged to Audio Source, and the *VolumeOn* snapshot to SceneManager.
0 commit comments