Creating a Virtual Piano with UI in Unity 2021 URP

GameDev Dustin
3 min readSep 8, 2022

--

In this article, we’ll create a simple virtual piano with Unity’s UI system.

Scene Setup
We’ll need to add a Canvas element to get started.
Add UI Image element below that and rename it to “background”.

Align the Background element with center and use Alt to position it at the center of the Canvas.

Then add an empty game object and named “Keys” as a child of the Background element.

Then create one UI Image element as a child of it.
Rename that UI Image to “Key_1”.

The VirtualPiano Class/Script
We won’t need much coded to pull this off.

Create a new C# script and name it “VirtualPiano”.

We’ll need three serialized fields to hold our Audio Clip, Audio Source, and pitch.

Our only method, PlayKey(), will verify that the Audio Source and Audio Clip variables are assigned before assigning the pitch of the particular key (game object) that script is assigned to.

Than we’ll simply use “.PlayOneShot()” to play the Audio Clip.

On the “Key_1” button, assign the VirtualPiano script as a component.

Next, add the Audio Source component and assign it to the Virtual Piano script component.

Now set the pitch to the default, “1”.

Under the “Button” component of the “Key_1” element, find the “On Click ()” section which is tied to he Unity Event system and click the “+” button.

Drag the “Key_1” element into the available field and then select the attached VirtualPiano script from the drop down.
Select the “PlayKey()” method we created earlier.

Now let’s create 5 more keys by duplicating our current key (UI Image element).

Let’s go ahead and spread out they keys and then resize them to fit our background.

Now let’s give each key a different color by going to the “Button” section of each key and setting the “Normal Color” field.

Now add a variation of each key’s color to the “Highlighted Color”, “Pressed Color”, and “Selected Color” fields.

Lastly, we need to give each key its own unique pitch.

Now, we should be able to hit play and enjoy our virtual piano!

See you in the next article!

--

--