Hi2,
I have (a very simple, i think) problem. How do I detect & interact with the Ui Element that is currently being "raycasted" ?
The figure below shows what i want to achieve: 
I have this code from Unity Documentation
void FixedUpdate()
{
int layerMask = 1 << 8;
// This would cast rays only against colliders in layer 8.
// But instead we want to collide against everything except layer 8. The ~ operator does this, it inverts a bitmask.
layerMask = ~layerMask;
RaycastHit hit;
// Does the ray intersect any objects excluding the player layer
if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, Mathf.Infinity, layerMask))
{
Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * hit.distance, Color.yellow);
Debug.Log("Did Hit");
}
else
{
Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * 1000, Color.white);
Debug.Log("Did not Hit");
}
}
but it just allow me to raycast a 3D object(with collider).
I heard about graphic raycaster and raycast all but not sure how to use it.
If possible, I don't want to attach extra script or extra event to the UI element(cause I have a lot of UI Element)
Thank you very much in advance for your input! :D
var eventData = new PointerEventData(EventSystem.current);
eventData.position = Input.mousePosition;
var results = new List<RaycastResult>();
EventSystem.current.RaycastAll(eventData, results);
if(results.Where(r => r.gameObject.layer == 6).Count() > 0) //6 being my UILayer
{
Debug.Log(results[0].gameObject.name); //The UI Element
}
Hope this helps =)
Make sure your UI elements have a 2D collider that's not a trigger.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With