Scratch To Unity: Sound

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:

audioSource.Play();

And you could yield based on the clip’s length:

yield return new WaitForSeconds(audioSource.clip.length);

Or yield each frame that the audio source is still playing:

while (audioSource.isPlaying)
{
    yield return null;
}

You can also use a “WaitWhile” command like this:

yield return new WaitWhile(() => audioSource.isPlaying);


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:

public AudioClip clip;
public AudioSource source;

You assign the clip to the source in code like this:

source.clip = clip;

You begin playing the sound like this:

source.Play();


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:

AudioSource[] sources = GetAudioSources();
foreach (AudioSource source in sources)
{
    source.Stop();
}

But in many cases if you want to Stop all sounds, it might be simpler to modify the “AudioListener”:

AudioListener.pause = true; // Pause all sounds
AudioListener.pause = false; // Resume all sounds


var audioSource = GetComponent<AudioSource>();
audioSource.pitch += 0.1f;


var audioSource = GetComponent<AudioSource>();
audioSource.pitch = 1f;


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.

var audioSource = GetComponent<AudioSource>();
audioSource.pitch = 1f;
audioSource.panStereo = 0f;
// etc


var audioSource = GetComponent<AudioSource>();
audioSource.volume -= 0.1f;


var audioSource = GetComponent<AudioSource>();
audioSource.volume = 1f;


var audioSource = GetComponent<AudioSource>();
var volume = audioSource.volume;

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!

Leave a Reply

Your email address will not be published. Required fields are marked *