How do I get sprites to behave as buttons

I need to make a square tile behave as a button. I attatched a “Button (script)” to it and created an animation, Auto Generated the animation, and created an animation for the Pressed state, but even if I press the sprite, only the Normal (idle) animation runs .
I’ve searched for 6 hours now and I can’t seem to find anything.
I found some things about attatching a BoxCollider2D, but I doesn’t work. I think I have to relate the On Mouse Down to the “pressed” state.

Can I even turn a sprite into a button with the button script ?
I’ve searched everywhere,could somebody help me with a bried answer please? Thanks .

The Button component can only work with UI elements. You would need to create an Image object underneath a Canvas parent for the Button component to automatically work.

For a Sprite (GameObject with normal Transform and SpriteRenderer), you cannot use the Button component built-in. You can add a Collider set to Trigger to the object, and add a custom script that implements the Unity functions OnMouseDown, OnMouseUp, etc. to trigger logic or play animations.

2 Likes

I was going to chime in and say this, but you beat me to it. Shakes fist

We have some great UI video tutorials on our Learn page. Here is one specifically for buttons!

1 Like

Thanks,that helps, now I can focus on finding alternatives .:slight_smile:

OK, but don’t be afraid of simply coding the button behavior yourself. You just need to keep track of whether the button is currently “pressed” or not. A rough sketch of the code is this:

  • if not pressed, watch for a pointer-down to happen on the sprite, and set pressed=true

  • if pressed:

  • track the pointer position; draw the “pressed” version when the pointer is over the sprite, and the normal version when it is not

  • watch for a pointer-up to happen; if the pointer is over the sprite, fire the Action event, redraw the normal version of the sprite, and (in any case) set pressed=false

That’s about it. It’s a page of code or less.

2 Likes

I don’t know if this Thread is still active but, can you still use Listeners without the “Button component”?

Can you explain what you mean by Listeners?

Hi All,
I used a paid tool called 2DToolKit.
I can handle sprites as buttons without adding a UI component.

Hi @rahul_noob

Old thread, but you don’t have to buy an asset.

You can add a script with Pointer event listener like on pointer click to your sprite. Or use Event Trigger component.

Then add collider 2d to your sprite.

Then add Physics 2d raycaster to your camera.

And finally, also have typical UI system components in scene (event listener and input module).

Pretty much the same setup as with UI elements, with the exception of raycaster and collider.

It was already mentioned by @LiterallyJeff

2 Likes