Search Unity

Instatiate to random position a prefab Button without colliding each other

Discussion in '2D' started by szajduk95, Oct 27, 2020.

  1. szajduk95

    szajduk95

    Joined:
    Oct 27, 2020
    Posts:
    1
    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!
     
  2. Cornysam

    Cornysam

    Joined:
    Feb 8, 2018
    Posts:
    1,466
    Try something like this, first thing i googled:

     
  3. eses

    eses

    Joined:
    Feb 26, 2013
    Posts:
    2,637
    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.

    https://docs.unity3d.com/ScriptReference/RectTransform.GetWorldCorners.html

    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.

    https://docs.unity3d.com/ScriptReference/RectTransform.html

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