- Home /
Bounds.Encapsulate no longer working?
Hi there, I'm trying to get the size of all the colliders put together on an object, but for some reason it only gets the bounds of the first collider. I've checked and it is running through all the colliders attached to the object, but no matter how I change the colliders, or how much manual garbage values I throw into the Encapsulates function the "bounds" variable doesn't change from the first one.
bounds = new Bounds();
Collider2D[] colls = GetComponents<Collider2D>();
if (colls.Length > 0)
{
foreach (Collider2D coll in colls)
{
if (!coll.isTrigger)
{
if (bounds.extents == Vector3.zero)
{
bounds = coll.bounds;
}
bounds.Encapsulate(coll.bounds);
}
}
}
Answer by Arkaid · Jun 30, 2016 at 02:34 PM
I had something similar happening here. Bounds is a structure, not a class, so it gets passed by value. If you declared bounds as a property of your class, each time you reference it you're getting a copy.
So here, you're setting it up for the first time (assignment)
bounds = coll.bounds;
but here,
bounds.Encapsulate(coll.bounds);
you're getting a copy of bounds and using Encapsulate on that copy, so the original remains untouched.
What you want to do is work on a local instance of Bounds, and assign the result to your class property, like so:
Bounds tempBounds = new Bounds();
Collider2D[] colls = GetComponents<Collider2D>();
if (colls.Length > 0)
{
foreach (Collider2D coll in colls)
{
if (!coll.isTrigger)
{
if (bounds.extents == Vector3.zero)
{
tempBounds = coll.bounds;
}
tempBounds.Encapsulate(coll.bounds);
}
}
}
bounds = tempBounds; // update class property