Search Unity

Calculating bounds of object error

Discussion in 'Scripting' started by kityanlam3, Jun 8, 2016.

  1. kityanlam3

    kityanlam3

    Joined:
    Feb 2, 2016
    Posts:
    41
    I have a function that creates gameobjects from scratch, adding boxcolliders manually and all that. I also expand the boxcollider to encapsulate the entire gameobject and it works for one object but when I add more objects the boxcollider for the newly created object will take the previous object's boxcollider's size and add it to itself. As this goes on, the box colliders become massive.

    upload_2016-6-8_11-23-47.png
    In this example, you can see the red box has a perfect sized collider but then the white box has a huge one. I just want the boxcollider to fit each object.

    Here's the code.

    Code (CSharp):
    1. public void SetFurniture(GameObject b)
    2.     {
    3.         HoldingObject = true; //a bool to see if holding an object
    4.         camera.cameraFreezerot = true; //freeze camerarotation
    5.         currentfurniture = b.transform;
    6.        
    7.        //adding components
    8.         Rigidbody d=b.AddComponent<Rigidbody>();
    9.         d.isKinematic = true;
    10.         d.useGravity = false;
    11.         BoxCollider s = b.AddComponent<BoxCollider>();
    12.         s.isTrigger = true;
    13.  
    14.  
    15.        
    16.         Renderer[] renderers = b.GetComponentsInChildren<Renderer>();
    17.         Debug.Log(renderers.Length);
    18.         foreach (Renderer rend in renderers)
    19.         {
    20.             totalsize.Encapsulate(rend.bounds);
    21.         }
    22.  
    23.         s.size = totalsize.size;
    24.  
    25. b.tag = "GroundFurniture";
    26.         fm.groundfurniture.Add(b);
    27. }
    28.  
    29.  
     
  2. kityanlam3

    kityanlam3

    Joined:
    Feb 2, 2016
    Posts:
    41
    I added a totalsize.size = new Vector3(0,0,0); at the end and it seems to work fine. :p
     
  3. nelson218

    nelson218

    Joined:
    Jun 7, 2016
    Posts:
    11
    always beware while using global variables. Try not to use them, and in case if you want to use them, try to reset them