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?
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.
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");
}
}
Just do
void OnMouseOver(){
//play audio
}
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
– savlonidk 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
– IremAkkin