UI Button - Play sound when highlighted???

I’m playing around with the new UI systems in unity, and i can’t seem to figure out how to play sounds anymore when the mouse hovers over menu buttons. All my searching leads me to event triggers but i still cant make it work. Heres my code:

using UnityEngine;
using System.Collections;

public class SceneChanger : MonoBehaviour {

public AudioClip happy;
public AudioClip sad;

public void ButtonHighlighted(int track)
{
    if (track == 1)
    {
        audio.PlayOneShot(happy);
        Debug.Log("Play button highlighted");
    }
    else
    {
        audio.PlayOneShot(sad);
        Debug.Log("Quit Button Highlighted");
    }
}

}

Anyone help?

This video is a really simple and customizable way of handling triggers from event data (mouse enter, exit etc..... And you won't need a script on every interactable UI GameObject (like the answer given by AlwaysSunny. -- https://www.youtube.com/watch?v=YAnLL1MCNoI

idk why but the video savlon sent is invalid but i found a little video that shows we can do these whole process without the script and just do itwith the scene inspector in an easy way Maybe its what the video they said but here is the link: https://www.youtube.com/watch?v=gR8ae41UlXY

3 Answers

3

Use Add Component button under your UI Button’s inspector window. Add Component/Event/Event Trigger. Then under Event trigger, Add new /PointerEnter. Rest is same as On Click sound. Make a game object/audio source, add your clip to source. Uncheck Play on awake. Press + sign on your Event Trigger (Script) under your UI Button inspector. Referance your new audio source object on your new trigger event, then for function, choose AudioSource.Play.

I'd like to add that this option works so much easier. The new unity UI is really something. Thank you!!

Does it also work for console or is it just for PCs?

The problem is I want to make different sound when hovering and pressing. But I can't. Because even if I add 2 different audio source to make 2 different audio, object just taking first audioclip of audiosource

This is an excerpt from the script I add to my buttons to get sounds. You’ll need to edit it for your specific needs, of course. Implement the IPointerEnterHandler interface, and create an OnPointerEnter method with the same signature seen below.

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections;

public class UIButtonSoundEvent : MonoBehaviour, IPointerEnterHandler, IPointerDownHandler {    

	public void OnPointerEnter( PointerEventData ped ) {
	    SoundManager.Play("MouseOverButton");
	}

	public void OnPointerDown( PointerEventData ped ) {
	    SoundManager.Play("MouseClickButton");
	}    
}

Iused this in combination with a Gameobject solely responsbile for playing sound for UI Elements. Worked very well and only required me to add the scripts to all buttons

Just do

void OnMouseOver(){
//play audio
}

Doesn't work on UI objects.