1
\$\begingroup\$

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

\$\endgroup\$
  • \$\begingroup\$ "since UI buttons move with camera" this is incorrect. They move with the camera if and only if you ask them to by setting your Canvas mode to "Screen Space - Overlay" or "Screen Space - Camera". If you keep your Canvas in World Space then it is drawn as part of your 2D/3D world like sprites and meshes, not relative to the current camera view. \$\endgroup\$ – DMGregory Jul 11 at 10:55
2
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ Ok let me try the World Space Canvas. And I will post the update here. \$\endgroup\$ – thirteen4054 Jul 11 at 11:05
  • \$\begingroup\$ I used the World Space Canvas and added a transparent button over my objects and it works awesome thanks. \$\endgroup\$ – thirteen4054 Jul 11 at 12:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.