1
\$\begingroup\$

I'm trying to get the bounds of an object and put a box around it.

Sounds simple right? I just encapsulate all the bounds together and use its center and size to do so.

But the problem is one corner of the box is always at the center of the scene, like a part of the object is there, unless the center of the scene is in the bounds.

This is when object is at the center Screenshot of a couch with green bounding box around it

This is when it isn'tScreenshot of a couch off to the side, with a much larger bounding box extending to the left and behind it

This is the code i'm using:

    public static Bounds Calculate(Transform TheObject)
    {
        Renderer renderer = TheObject.GetComponent<Renderer>();
        Bounds combinedBounds = new Bounds();
        if (renderer != null)
            combinedBounds = renderer.bounds;
        var renderers = TheObject.GetComponentsInChildren<Renderer>();
        foreach (Renderer render in renderers)
        {
            if (render != renderer) combinedBounds.Encapsulate(render.bounds);
        }
        return combinedBounds;
    }
\$\endgroup\$
4
  • 2
    \$\begingroup\$ When you initialize combinedBounds = new Bounds(), does this default constructor give you a set of bounds around (0, 0, 0)? This might be the source of your origin point forcing its way into your bounds. \$\endgroup\$
    – DMGregory
    Dec 20, 2016 at 15:16
  • 1
    \$\begingroup\$ thank you @DMGregory that was the problem. should I delete this question now that I now how simple the mistake was? \$\endgroup\$
    – Henjin
    Dec 20, 2016 at 15:24
  • 2
    \$\begingroup\$ Nah, someone else might have the same issue and go looking for ideas. Feel free to write up how you solved it in an answer, and include your modified code. \$\endgroup\$
    – DMGregory
    Dec 20, 2016 at 15:26
  • \$\begingroup\$ That said, you should actually post the solution as an answer, and accept it, so others know it actually was the solution. \$\endgroup\$
    – Gnemlock
    Dec 20, 2016 at 23:25

1 Answer 1

2
\$\begingroup\$

As @DMGregory said the problem was that if I create a new bound to initialize the variable, it means I'm creating a bound that is located in the center of the scene and has 0 extents. So all I had to do was to rearrange the order of my code :

    public static Bounds Calculate(Transform TheObject)
    {
        var renderers = TheObject.GetComponentsInChildren<Renderer>();
        Bounds combinedBounds = renderers[0].bounds;
        for(int i = 1; i < renderers.Length; i++)
        {
             combinedBounds.Encapsulate(renders[i].bounds);
        }
        return combinedBounds;
    }
\$\endgroup\$
1
  • \$\begingroup\$ Don't forget to pick this as your answer :) \$\endgroup\$ Dec 22, 2016 at 10:42

You must log in to answer this question.

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