- Home /
 
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
What's the type of the object that you are using this on? (2d sprite,...)
Answer by YoucefB · Oct 07, 2017 at 02:52 PM
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;
         }
     }
 
              thanks, yeah I was trying different methods and they both didn't work. Ill try this one though
what about a screenshot of the recttransform. and from where are you calling this method? ( ResizeColliders() )
Answer by konsnos · May 23 at 09:20 AM
Try this for resizing
 BoxCollider2D boxCollider2D = GetComponent<BoxCollider2D> ();
 RectTransform rectTransform = GetComponent<RectTransform> ();
 var rect = rectTransform.rect;
 boxCollider2D.size = new Vector2 (rect.width, rect.height);
 
              Your answer
 
             Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Mouse Player Movement Controller 1 Answer
How to use 2D pathfinding with vector 2 0 Answers

