Calculating bounds of object error

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.


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.

public void SetFurniture(GameObject b)
    {
        HoldingObject = true; //a bool to see if holding an object
        camera.cameraFreezerot = true; //freeze camerarotation
        currentfurniture = b.transform; 
       
       //adding components
        Rigidbody d=b.AddComponent<Rigidbody>();
        d.isKinematic = true;
        d.useGravity = false;
        BoxCollider s = b.AddComponent<BoxCollider>();
        s.isTrigger = true;


       
        Renderer[] renderers = b.GetComponentsInChildren<Renderer>();
        Debug.Log(renderers.Length);
        foreach (Renderer rend in renderers)
        {
            totalsize.Encapsulate(rend.bounds);
        }

        s.size = totalsize.size;

b.tag = "GroundFurniture";
        fm.groundfurniture.Add(b);
}

I added a totalsize.size = new Vector3(0,0,0); at the end and it seems to work fine. :stuck_out_tongue:

always beware while using global variables. Try not to use them, and in case if you want to use them, try to reset them