Matching an object's size

Hi,
I’m trying to scale an object (with a rigidbody) to match the exact size of another object (with no rigidbody, just a mesh renderer).

I have tried collider.bounds.size = object2.renderer.bounds.size; which gives me the error CS1612: Cannot modify a value type return value of `UnityEngine.Collider.bounds’. Consider storing the value in a temporary variable

I looked up this error and tried this:

Vector3 temp = collider.bounds.size;
temp.x = object2.renderer.bounds.size.x;
temp.y = object2.renderer.bounds.size.y;
collider.bounds.size = temp;

but I think I’m doing something stupid here because I still get the same error.

Anyone know how I can do this please?

The error is generated when you try to modify a “value type”, which in this particular cas means a struct.

When a function or property return a value types (as structs are), you always get a copy instead of the original. So changing that copy would not make sense, because you want to change the original bounds of the renderer - not just a copy.

The struct that the compiler is complaining about are “bounds”, not “size”. (Although size is a vector, which is an struct too)

So when you do collider.bounds.size = object2.renderer.bounds.size you are assigning a new size to a copy of the colliders bounds. Which is most definetely not what you would expect. C# emits an error for that.

If at all, you would have to assign the bounds - property itself.

// doesn't work either
collider.bounds = new Bounds(collider.bounds.center, object2.renderer.bounds.size);

But then you will get another error, namely that “bounds” is a read-only property.

To change collider sizes, you can either use some specific collider functions (e.g. if you are using a CapsuleCollider, it has some properties as “height”, “radius” and “center”). Or you can change the transform - component that the collider is attached to, which is also used by the collider itself.

// changes the scale of the transform, which is also used by the collider
transform.localScale = object2.renderer.bounds.size