- Home /
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=YAnLL1$$anonymous$$CNoI
Answer by KamilSeven · Jan 23, 2016 at 01:29 AM
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!!
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
Answer by AlwaysSunny · Apr 26, 2015 at 06:01 PM
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");
}
}