Raycast on UI Image

Raycast is a typical way to cast a beam from the camera to the designated position as a use of detecting click or touching.

In general, raycast on a 3D object can be implemented as the following:
(just remember an object with a collider can be hit)

if (Input.GetMouseButtonDown(0)) {

    // a ray from camera to the mouse click position
    Ray clickRay = Camera.main.ScreenPointToRay (Input.mousePosition);
    RaycastHit clickRayhit;
    
    // raycast
    if (Physics.Raycast (clickRay, out clickRayhit)) {
        Debug.Log (clickRayhit.collider.gameObject.name); // print who's hit
    }

}

What about raycast on UI Image? Rather than adding colliders to UI components, I think GraphicRaycaster would be a better solution.
(just remember a UI Image with Raycast Target checked can be hit)

// remember to add the following two
using UnityEngine.UI;
using UnityEngine.EventSystems;

if (Input.GetMouseButtonDown(0)) {

    // set ups
    m_PointerEventData = new PointerEventData(m_EventSystem);
    m_PointerEventData.position = Input.mousePosition;
    List<RaycastResult> results = new List<RaycastResult>();
    
    // raycast
    m_Raycaster.Raycast(m_PointerEventData, results);
    
    foreach (RaycastResult result in results) {
        Debug.Log (result.gameObject.name); // print who's hit
    }

}

Last but not the least, what if you want to neglect the transparent part of the image and only trigger raycast events on the opaque part? I've tried the official guide using Image.alphaHitTestMinimumThreshold, but I never success (? maybe some of you can teach me)

Fortunately, I found the wanted wheel Alpha Raycaster. And I will introduce how I use it in my project:

Voilà! Only have to check the Read/Write Enabled of the sprite texture, and add the component Alpha Check to the UI image object

f:id:fervor:20180627194620p:plain

I cannot provide my project since the Alpha Raycaster isn't free. If you are struggling to implement the same function, I highly recommend you to have this wheel.