Correct button creation

Hi guys,
I have a question about buttons. I instantiate 50-60 gameobjects in my game, which on the one hand have a sprite/image and on the other hand should function as buttons. What is the best way to do this? I am a fan of button components and have therefore created a canvas on the game object and added an image and button components in the child object. Is this a good method or can it lead to performance problems if you have 50-60 canvas in the game? The second method I can think of would be to use Raycast to detect which object was clicked on. But I have never done that before, so I don’t know if it is better or more complicated.
Kind regards

You shouldn’t need 50 canvases for 50 buttons, you can put multiple UI elements under the same Canvas.

1 Like

Yes thats right. But in this case it is an 2D enemy. And if I click on it, I wanna open a window with information about this enemy.Thats why I guess it is not possible to put multiple Object under the same Canvas. Or should I simply spawn them unter an object with a canvas? It is this typical rts thing, just in 2D.

You can absolutely spawn multiple child objects of a canvas. The UI system would be useless if you couldn’t.

That said you probably don’t want your enemies to be UI elements, especially in an RTS game. There are lots of ways to register a click on regular game objects, depending on input system. Should be a simple search away from learning how.

2 Likes

Yeah sorry RTS was the wrong word. It is a tower defense game. And after I have placed a tower, it should be possible to click the tower to show informations. They need nothing else so i thought to create them as gameobjects with a canvas ,image and button on it should be enough. What would you prefer?

You probably still want them to be regular game objects, rather than UI objects with a RectTransform.

First reason that comes to mind is that positioning RectTransforms is not straight-forward at all, as opposed to positioning normal game objects. You also won’t be able to use any physics queries, which would make a lot of things much harder. I would imagine there’s a bunch more that don’t immediately come to mind; I imagine certain visual effects would be harder/impossible too.

Unity’s 2D system is pretty robust so you should take advantage of it.

Again there’s a number of ways to select regular game objects.
For the old input system: Unity - Scripting API: MonoBehaviour.OnMouseDown()
Or for the new input system: Interface IPointerClickHandler | Unity UI | 1.0.0

1 Like