Changing the radius of a 2d circular collider

I’ve been experimenting with something lately and I wanted to change the radius of a circle collider using code at runtime and not manually to change it in the editor is there any way of doing this?

I did some research and I’m not sure how to achieve this.

This is what I’ve been trying to do:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerStatus : MonoBehaviour
{
    public float hp = 100;

    public float attack = 20;
    public float attackSpeed = 10;
    public float attackRange = 15;

    private Collider2D attackRangeCollider;
    private Collider2D playerCollider;

    // Start is called before the first frame update
    void Start()
    {
        attackRangeCollider = GetComponent<CircleCollider2D>();
        playerCollider = GetComponent<BoxCollider2D>();
       

        //Vector2 radiusVector = new Vector2(attackRange, attackRange);

        attackRangeCollider.bounds.Expand(attackRange);

    }

    // Update is called once per frame
    void Update()
    {


        attackRangeCollider.bounds.Encapsulate(new Vector3 (transform.position.x + attackRange, transform.position.y + attackRange, transform.position.z));

    }
}

See your line 13? That declares the collider as a generic Collider2D.

If you change that variable type to CircleCollider2D, then you can use that variable to access the circle-specific property called .radius and get what you want.

Also: take out the fiddling with the bounds on line 25. Bounds will almost never get what you want…

Thanks so much, I’ve been trying to find out how to do this. I saw this property in the unity documentation and I tried to find it but I could not find where it was. This helped a lot. Thanks so much.

1 Like