How I made a virtual piano in Unity

Tyler Smallwood
3 min readAug 28, 2023

Objective: Explain how to use buttons to make piano sounds.

When we create buttons, the button component has an event area. We can use this to call a method to play sounds. To start lets create a button by going in the hierarchy and right click → UI → Button.

When the button is created, go ahead and either delete the text that is a child or disable it.

For this article I made the buttons a little long to look like a piano key.

Now let’s create a C# script. Inside the script let’s get a variable to hold the Audio Source, Audio Clip, and a float for pitch.

Now let’s create a public method to call when we hit the button. Inside this method we will set the audio’s source to the pitch value. Next we will call a AudioSource method, PlayOneShot() and pass in the audio clip.

Next we need to set up the button. On the button we created, let’s add the script, and an Audio Source. We can pull in the Audio Source to the script variable and add in the piano key clip. We can also set the pitch to one for this button.

We can create a new Audio Mixer for the piano sounds to play out of. To do this we need to open the Audio Mixer. Top of the window click Window → Audio → Audio Mixer, or just hit ‘Ctrl + 8’ on your keyboard.

In the Audio Mixer Window, on the left side, go down to Group and hit the + button and name the new group.

On the Button we just need to add in the piano mixer to the button.

With this our piano key is done but it is only one pitch of a piano. To fix this let’s duplicate the button a couple of times.

For each button adjust the pitch by .1.

That is it. Now our keys can play music! Thank you for reading and have a wonderful day!

--

--

Tyler Smallwood

I am passonate on learning to program and use Unity to become a skillful Unity Developer