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.
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