Sprite button not triggering "On Click()" event -Unity

by thirteen3054   Last Updated July 11, 2019 11:13 AM - source

Hi have created some buttons from sprite and I added image and button components on it.

enter image description here

enter image description here

I am just using sprites because In my game the camera can be moved on x and y. But I don't want my button to move and since UI buttons move with camera that is why I am not using them.

Here is the GIF to explain the scene:

enter image description here

Tags : unity c# 2d sprites

Answers 1

It looks like you tried to attach a SpriteRenderer to your button to render its visual in your game scene rather than as part of the UI. This means that where the player sees the button, and where Unity thinks the clickable UI is, have no relationship to one another.

The UI Button On Click event fires only on clicks on the UI Button itself.

If you click the SpriteRenderer, that is not part of the UI system, it is not the same as clicking on the UI button.

To detect a click on a Sprite, add a Collider to it, and use a script to listen for clicks:

void OnMouseDown() {
    // Do the thing.

Note that the presence of this method forces Unity to fire a ray into your scene every frame to track mouse interaction with colliders in your scene, so it does have a performance cost.

Or, you can click the button itself, by getting rid of your SpriteRenderer and instead using a World Space Canvas to draw your actual UI button where you want it in the scene. Then you have all the power of the normal UI system, and the freedom to position it anywhere in your world that you want it to go.

July 11, 2019 11:00 AM

Related Questions

gradient shader on circular sprite

Updated June 20, 2015 23:05 PM

Why my dynamically generated Sprites overlap?

Updated April 15, 2015 20:05 PM

Unity 2D - scale sprite according to screen width

Updated April 17, 2015 20:05 PM