Object size changing issue (w/ box collider)

Hi, currently I’m using a simple script to change the size of a 2d object, which has a rigidbody2d and boxcollider2d attached. Here’s the script:

public float growspeed = 0.75f;
	float scale = 0;
	public float duration = 5f;
	BoxCollider2D collider;
	// Use this for initialization
	void Start () {
		collider = GetComponent<BoxCollider2D> ();
	}
	
	// Update is called once per frame
	void Update () {
		duration -= Time.deltaTime;
		scale += growspeed * Time.deltaTime;
		transform.localScale = new Vector3 (scale, transform.localScale.y, 0);
		if (scale > 1) {
			collider.size = new Vector2 (scale, collider.size.y);
		}
		if (duration <= 0) {
			Destroy (this.gameObject);
		}
		
	}
	void OnCollisionEnter2D(Collision2D other){
		if (other.gameObject.tag == "Player") {
			Destroy (this.gameObject);
		}

As you can see in the script, when I change the size of the object I have to also change the size of the box collider to maintain collision detection - however, when I change the size of the box collider as well, it causes the object to randomly change size and move its position downwards - effectively it kind of distorts. If I don’t change the size of the boxcollider, then the object smoothly and normally changes size. How would I be able to fix this? Any help would be appreciated.

You shouldn’t really have to scale the collider, it automatically scales with the transform component. As long as the GameObject with the collider is the same as the one with the scaled transform or one of its children, you wouldn’t have to additionally scale the collider.

In other words: The collider’s actual size is transform.scale * collider.scale.

Two thoughts though:

  1. You set transform.localScale.z to 0. Even in a 2D game, never do this. The default value for a scale component is 1 and setting it to 0 can have weird consequences. Even in a 2D game.
  2. Since you have no positioning or rotation in your code, I assume that the moving and distorting you are describing comes from another script or through the object’s hierarchy. Try to put this code alone on a GameObject in an otherwise empty scene and see what happens.