This post provides a handy reference guide to go from Scratch’s “Sound” category of code blocks to C# with Unity.
Code Blocks
Click on the picture of any of these Scratch code blocks to see how to write similar code statements in C#.
You program over time using a Coroutine. Unfortunately there is no “Wait For Sound” statement that is built-in, but you have a few ways to simulate something similar. Let’s assume you are able to obtain a reference to an “AudioSource” component which already is assigned the “AudioClip” you want to play.
You can begin the playback of the sound like this:
[csharp]
audioSource.Play();
[/csharp]
And you could yield based on the clip’s length:
[csharp]
yield return new WaitForSeconds(audioSource.clip.length);
[/csharp]
Or yield each frame that the audio source is still playing:
[csharp]
while (audioSource.isPlaying)
{
yield return null;
}
[/csharp]
You can also use a “WaitWhile” command like this:
[csharp]
yield return new WaitWhile(() => audioSource.isPlaying);
[/csharp]
Suppose you have a reference to an “AudioSource” component which will play the sound as well as the “AudioClip” that you want to have played. You can obtain them through code or through the Unity Inspector:
[csharp]
public AudioClip clip;
public AudioSource source;
[/csharp]
You assign the clip to the source in code like this:
[csharp]
source.clip = clip;
[/csharp]
You begin playing the sound like this:
[csharp]
source.Play();
[/csharp]
If you have a convenient reference to all of your audio sources, then you could loop over them and call the “Pause” or “Stop” method on each:
[csharp]
AudioSource[] sources = GetAudioSources();
foreach (AudioSource source in sources)
{
source.Stop();
}
[/csharp]
But in many cases if you want to Stop all sounds, it might be simpler to modify the “AudioListener”:
[csharp]
AudioListener.pause = true; // Pause all sounds
AudioListener.pause = false; // Resume all sounds
[/csharp]
[csharp]
var audioSource = GetComponent
audioSource.pitch += 0.1f;
[/csharp]
[csharp]
var audioSource = GetComponent
audioSource.pitch = 1f;
[/csharp]
There is no equivalent for this code block. You can obtain a similar result by simply setting all effect variables to their default values, whether they had been modified or not.
[csharp]
var audioSource = GetComponent
audioSource.pitch = 1f;
audioSource.panStereo = 0f;
// etc
[/csharp]
[csharp]
var audioSource = GetComponent
audioSource.volume -= 0.1f;
[/csharp]
[csharp]
var audioSource = GetComponent
audioSource.volume = 1f;
[/csharp]
[csharp]
var audioSource = GetComponent
var volume = audioSource.volume;
[/csharp]
Summary
This should cover all of the code blocks in Scratch’s “Sound” category. If you have any questions about this reference guide feel free to ask below.
If you find value in my blog, you can support its continued development by becoming my patron. Visit my Patreon page here. Thanks!