How to use colliders on UI images using Screen Space Overlay?

I’m trying to create a custom button by adding a 2D collider to a UI image object. The canvas that is being used is set to Screen Space Overlay. Unfortunately this does not seem to work as clicking the collider never registers.

I tried it with a clean slate and can’t get it to work, I have done the following:

  • Create a new scene
  • Add a canvas object and set it to ‘Screen Space - Overlay’
  • Add an image object to the canvas
  • Add a box collider 2D to the image object and resize it to fully encase the image
  • Set the ‘Is Trigger’ option on the collider
  • Add a script to the image object that has a ‘OnMouseUpAsButton()’ method, this methods writes a line the the debug.log
  • Upon clicking the button nothing happens

If I change the canvas to ‘World Space’ mode it does work, but I just can’t seem to get it to work in overlay mode.

Any ideas what I’m doing wrong here?

And why not using a simple button ?? You can set an image to the button and remove the text ... Otherwise, use a Event trigger on the image.

3 Answers

3

Okay if you are using anchors on this image it’s position will be changed in different screens that make your game weird that distance between collider and trigger won’t be the same on the different screens so it’s better to use sprites instead.

You don’t need collider.
Add Evet Trigger component to your Image.

click “Add New Event Type” button and choose event type.
if you want the event to run when mouse click choose pointer click

and then create script add a method which do what you want when image is be clicked

131063-cavap2.png

after that create empty object
add the script to it as component
drag the obje to event trigger component of image and choose event method

I had a similar problem and found this hint: https://forum.unity.com/threads/canvas-collider2d-mouse-events.480363/

Important: I had to change the settings for the ui camera / Menu Camera from “Clear Flags: Don’t Clear” to “Clear Flags: Depth only” and I made sure the “Depth” of this camera was higher than the “Depth” of the main camera (explained here: Reddit - Dive into anything).

Maybe this approach helps someone else too.