Instatiate to random position a prefab Button without colliding each other

Hi everybody!

I am completely new in Unity and I am doing my first project in it. I am stucked at a point and I need some help.

I would like to instantiate prefab buttons to random position inside a canvas without colliding each other. I have tried several ways (intersect, collider2d, renderer, or just calculating the size and position of the button) but none of them worked for me, the buttons where always overlapping with each other (Of course I know I have done something wrong).

Could someone please help me out if there is a simple way to do this?

Thank you in advance!

Try something like this, first thing i googled:

Hi @szajduk95

Isn’t this a UI related question not a 2D question? Just saying - don’t expect too many answers in this sub forum…

One way is to get UI element RectTransform and get its rectangle world corner positions. Then compare two of those.

BTW - you rarely need to use Colliders for UI.

Also, RectTransform itself has a rect value so you might also use that in some cases.

And knowing that your objects overlap won’t do anything itself, you then have to move your UI element manually or get a new position somehow, but I have no idea what you are doing…