Changing the size of a BoxCollider2D at runtime.

I am trying to implement a crouch mechanic for my 2D game and want to change the size of the boxCollider2D on the player upon pressing the ‘Crouch’ button.

I am trying to use the following code to change the size of BoxCollider2d at runtime but it is throwing an error.

BoxCollider2D boxCollider = GetComponent<BoxCollider2D>() as BoxCollider2D;
boxCollider.size.x = 6.4f;

“Cannot modify a value type return value of `UnityEngine.BoxCollider2D.size’. Consider storing the value in a temporary variable” is the error message being thrown.

I assume your crouch utilizes a sprite animation right? It might be easier just to adjust the collision box within your keyframe editor.

From a programming standpoint, you could also do:

boxCollider.size = new Vector2(6.4f, boxCollider.size.y);