Breakout Clone 6: Music
2023-03-15In my last post I added sound effects for the ball hitting the sides of play area, the blocks and the paddle.
Today I'm going to add some music. This won't take too long since most of the code is already in place.
First I'll add another AudioSource
to the SoundManager
and add a couple of methods to start & stop the music:
public class SoundManager : MonoBehaviour
{
public AudioSource sfxSource;
public AudioSource musicSource;
public static SoundManager instance = null;
[SerializeField] float lowPitchRange = 0.95f;
[SerializeField] float highPitchRange = 1.05f;
// I've omitted the Awake() and PlayRandomSFX()
// methods since they have not changed
public void PlayMusic() {
musicSource.Play();
}
public void StopMusic() {
musicSource.Stop();
}
These AudioSource
s are components on my GameSession
object that I've associated with the script by dragging-and-dropping them from the component, to the appropriate field in the UI. The sound effects didn't have an explicit AudioClip
assigned since we were picking a random one in PlayRandomSFX
. The music though will have an clip assigned to it, and I chose this one.
In my GameSession
script, we'll start playing the music when the game begins;
public class GameSession : MonoBehaviour
{
// Awake and LoadNextLevel have not changed
void Start() {
SoundManager.instance.PlayMusic();
}
}
This won't be the behavior for long. In my next post, I'm going to add in some screens to handle the main menu, a victory screen when the player has completed all the levels, and a failure screen when ball hits the bottom of the play area.