- Home /
Setting UI elements active while the mouse is already over them -- how to detect?
I have UI buttons that I set from active to inactive and vice versa. If the mouse cursor is over a button when the button is set active, then Unity does not immediately detect that the mouse is over the button. What is the best way to get around this?
I should also note that keeping the UI invisible instead of inactive isn't going to help me in this case. The position of the buttons are subject to change, and repositioning a button to underneath the mouse also results in the mouse not being detected.
Answer by Mmmpies · Jan 21, 2015 at 02:14 PM
Don't know if it's what you want but this will check the mouse point and return all the UI elements a Raycast passes through. The Text of the button will be the top one:
using UnityEngine;
using UnityEngine.EventSystems;
using System.Collections;
using System.Collections.Generic;
public class RaycastUI : MonoBehaviour {
public void RayCastingToUI ()
{
PointerEventData PED = new PointerEventData(EventSystem.current);
PED.position = Input.mousePosition;
List<RaycastResult> HITS = new List<RaycastResult>();
EventSystem.current.RaycastAll( PED, HITS );
foreach(RaycastResult hit in HITS)
{
GameObject go = hit.gameObject;
Debug.Log (go.name + " how many hit = " + HITS.Count);
}
}
}
This works quite well. I should add that for Buttons and Selectables, I can use the Select() function to select the Button/Selectable that the raycast picks up, and use EventSystem.current.SetSelectedGameObject(null) to deselect when the Raycast doesn't catch anything.
Your answer