Making a collider the size of the object it is attached to.

Hi there

I asked a question a while ago about resizing colliders. I got some replies but they didn’t seem to work. I have tried many different scripts, here are some different methods:

public void ResizeColliders()
    {
        RectTransform rt1 = (RectTransform)word1.transform;
        RectTransform rt2 = (RectTransform)word2.transform;
        RectTransform rt3 = (RectTransform)word3.transform;

        BoxCollider2D collid1 = word1.GetComponent<BoxCollider2D>() as BoxCollider2D;
        BoxCollider2D collid2 = word2.GetComponent<BoxCollider2D>() as BoxCollider2D;
        BoxCollider2D collid3 = word3.GetComponent<BoxCollider2D>() as BoxCollider2D;

        float col1w = rt1.rect.width;
        float col1h = rt1.rect.height;
        print(col1w);
        print(col1h);
        collider1.size = new Vector2(col1w, col1h);
        collider2.size = new Vector2(rt2.rect.width, rt2.rect.height);
        collider3.size = new Vector2(rt3.rect.width, rt3.rect.height);

        /**/
        //word1
        Destroy(word1.GetComponent<BoxCollider2D>());
        word1.AddComponent<BoxCollider2D>().isTrigger = true;
        //word2
        Destroy(word2.GetComponent<BoxCollider2D>());
        word2.AddComponent<BoxCollider2D>().isTrigger = true;
        //word3
        Destroy(word3.GetComponent<BoxCollider2D>());
        word3.AddComponent<BoxCollider2D>().isTrigger = true;
    }

all this seems to do is make the collider size 0.000001?

Could someone help please.
Tekman03

Try This:

public GameObject word1,word2,word3;
	void ResizeColliders()
	{
		GameObject words = new GameObject[]{word1,word2,word3}; // list of all words
		foreach (GameObject word in words) {
			BoxCollider2D bc = word.GetComponent<BoxCollider2D> ();
			RectTransform rect = word.GetComponent<RectTransform> ();
			bc.size = new Vector2 (rect.sizeDelta.x, rect.sizeDelta.y);
			bc.isTrigger = true;
		}
	}

Try this for resizing

BoxCollider2D boxCollider2D = GetComponent<BoxCollider2D> ();
RectTransform rectTransform = GetComponent<RectTransform> ();
var rect = rectTransform.rect;
boxCollider2D.size = new Vector2 (rect.width, rect.height);

it’s worked for me ! thanks a lot !