How to PLAY SOUNDS on MOUSE HOVER over UI elements in Unity

Introduction

It’s not necessary to create any script to play sounds on mouse hover over UI elements in Unity, you can do it just by adding specific objects to the scene and setting up components on UI elements such as buttons and any other interactable element.

If you prefer you can check the following short video from my YouTube channel, there you will find all you need to do to set up to play sounds on mouse hover over buttons and other UI elements.




What do we need to play sounds on mouse hover in Unity

We basically need three elements in order to play sounds on mouse hover over UI elements, we need a way to play the sound, we need the sound clip to be played and we need a way to detect the mouse hover event over UI elements. Let’s analyze these three elements:

Create at least one AudioSource object in the scene to play the sound

You can create easily a new AudioSource object simply by right clicking in the Hierarchy window, go to audio and click on “AudioSource”, this will create a GameObject with an AudioSource component assigned to it, this AudioSource has the “Play On Awake” checkbox enabled by default so you have to disable it, otherwise the Audio Clip will be played on Start.

Audio files to play on mouse hover

The file of the sound you want to play on mouse hover over UI elements, I suggest you use files with the WAV or OGG format. You can assign the AudioClip to the “Clip” variable in the AudioSource component.

Event trigger component attached on the UI element

We add an EventTrigger component to our button and this allows us to detect different events on this buttons, events like when the mouse cursor hovers over the button, also when a click is made on a button and many other options. In our case we are intereseted in the “Pointer Enter” event which is called when the mouse cursor hovers for the first time a UI element.



How to PLAY SOUNDS on MOUSE HOVER over UI elements in Unity

Once we cover all the previous three steps needed to play sounds on mouse hover in Unity we need to properly configure them. Here is a step by step guide to do it.

  • Select your button, in the inspector click on “Add Component” and look for the “Event Trigger” component.
  • Click on “New Event Type” in the Event Trigger and select “Pointer Enter”.
  • Create a new AudioSource GameObject (or use an existing one) and drag that GameObject to the “Pointer Enter” event.
  • Using the drop down menu of the “Pointer Enter” event go to the AudioSource section and look for the “PlayOneShot” function.
  • Drag the Audio file with the sound you want to play on mouse hover to the field of the “Play One Shot” function in the “Pointer Enter” event.
  • Play and test

Scroll to Top
Secured By miniOrange