JJChai
JJChai

Reputation: 117

Unity : How to make physics 2d raycaster go through UI elements?

I'm working on a mobile game. I'm having some problems with raycast and events.

I have a Screen Space Overlay Canvas with an UI image covering an area A. This image is set to transparent. Its purpose is for receiving user inputs.

Then I also have a world game object, a 2d sprite which is inside this area A. This sprite has a 2d box collider attached. This sprite acts as a world object (like a building) which user can pressed on.

I have set up a physics 2d raycaster to detect inputs on the 2d sprite. The problem I'm having is that the UI Image is apparently blocking off the 2d physic raycast onto the 2d sprite. Only when I turn off the UI Image, I will be able to receive the physic raycast event.

Help. Am I doing something wrong? I thought physics 2d raycast only reacts with 2d physics components?

enter image description here

This is the script attached to the 2d sprite.

using UnityEngine.EventSystems;
public class SpriteSelector : MonoBehaviour, IPointerDownHandler
{
    public void OnPointerDown(PointerEventData eventData)
    {
        Debug.Log("Sprite selected");
    }
}

This is the script attached to the UI Image.

using UnityEngine.EventSystems;
public class UIImageSelector : MonoBehaviour, IPointerDownHandler
{
    public void OnPointerDown(PointerEventData eventData)
    {
        Debug.Log("UI Image selected");
    }
}

Upvotes: 0

Views: 2515

Answers (2)

Linus
Linus

Reputation: 111

Since you seem to want to receive user inputs on the transparent background image too, you can just reorder the images in the hierarchy. The further down an object is relative to its siblings, the closer it is to camera, i.e. you can just move the button below the background in tbe hierarchy and the raycast should hit the button first.

Upvotes: 0

Dmitri Veselov
Dmitri Veselov

Reputation: 447

You need to uncheck Raycast Target

enter image description here

Upvotes: 1

Related Questions