2
\$\begingroup\$

I have two planes and I want to put both planes one after another so that I can form a road. I set them from the editor and that was very easy but I wanted to do this from code. So in the code:

void Start() {
  secondRoad.position = firstRoad.position;
}

But this just set the second plane in the center of the first plane, kind of overlapping. But I want the second plane to be placed next to the first plane where it ends right the edge of the first plane. How will I do this?

\$\endgroup\$
2
  • \$\begingroup\$ A plane has four edges. Which one do you want to place the second object at? \$\endgroup\$
    – DMGregory
    Mar 5, 2019 at 10:32
  • \$\begingroup\$ I want at the right edge \$\endgroup\$ Mar 5, 2019 at 11:06

1 Answer 1

3
\$\begingroup\$

Since your pivots are in the centers of the objects, to line up the planes edge to edge horizontally you'll need to shift to the right by...

  • half the width of the first (to reach its right edge from its center)
  • plus half the width of the second (to reach its center from its left edge)

In this case both objects are standard Unity planes (width = 10), so assuming you haven't scaled them, the two halves add up to one whole and we get:

float spacing = 10f;
secondRoad.position = firstRoad.position + Vector3.right * spacing;

To handle arbitrary shapes without a size known in advance, you can use the bounds of their renderers to determine the appropriate spacing.

\$\endgroup\$
2
  • \$\begingroup\$ it worked thanks, I want to know how would I find the width of any game object. \$\endgroup\$ Mar 6, 2019 at 10:40
  • 1
    \$\begingroup\$ See the link in the final paragraph. \$\endgroup\$
    – DMGregory
    Mar 6, 2019 at 11:54

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .