- Home /
How do I run a script when a button is highlighted
I just need to run a sound file when a button has been highlighted but not selected. How would I go about this?
Answer by Toon_Werawat · Apr 06, 2016 at 02:34 PM
If you use Sprite. Do what @KdRWaylander said. But if you use new unity ui.
Use Unity event system
By click at that button. And add component Event Trigger. Then add OnPointerEnter (When mouse highlight it)
But if you want as a script. Just add script to that button and set that button interacable to false (in case if script not work) Then just add interface to that class like this.
public class ButtonHighlight : Monobehaviour , IPointerEnterHandler
.....
public void OnPointer()
{
Debug.Log("Pointer over!);
}
IPointerHandler is need this namespace
using UnityEngine.EventSystem;
Hope that what you looking for... :)
Thanks this works great for the mouse but how would I use the event system to allow for using the keyboard?
Answer by Tohaveaname · Apr 12, 2016 at 04:37 PM
Turns out this was what I was looking for:
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
public class ReadMeButton : MonoBehaviour, ISelectHandler , IPointerEnterHandler
{
// When highlighted with mouse.
public void OnPointerEnter(PointerEventData eventData)
{
// Do something.
Debug.Log("<color=red>Event:</color> Completed mouse highlight.");
}
// When selected.
public void OnSelect(BaseEventData eventData)
{
// Do something.
Debug.Log("<color=red>Event:</color> Completed selection.");
}
}
Answer by KdRWaylander · Apr 06, 2016 at 02:10 PM
Hi,
Try this kind of message:
OnMouseEnter
OnMouseOver
OnMouseExit
http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseEnter.html http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseOver.html http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseExit.html
They're called in any script on the the gameobject (tho it must have a collider).
void OnMouseEnter () {
// [...]
}
Thanks guys this works great for the mouse but how would I use the event system to allow for using the keyboard?
How would you highlight a button with keyboard ? :o
You set the buttons in the Unity editor to have a explicit menu navigation then dictate where in the UI up, down, left, right on the keyboard will take you. You need to add .Select() function to highlight the first button you want in the menu.
Your answer
Follow this Question
Related Questions
Adding audio to gun shot 2 Answers
UnityWebRequest hangs on isDone but not always 1 Answer
Please help with playing music for button click 2 Answers
Multiple Cars not working 1 Answer
Delayed Button Sounds 0 Answers