Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interact with UI via RayCast Unity

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: enter image description here

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

like image 458
Kuroyuki Hikari Avatar asked Nov 01 '25 23:11

Kuroyuki Hikari


1 Answers

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.

like image 198
user5216459 Avatar answered Nov 03 '25 13:11

user5216459



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!