PSA: Collider Bounds Incorrect Until Phyiscs Update

Collider.bounds “The world space bounding volume of the collider”

But the value is wrong if you move a GameObject and then query the bounds in the same frame.

    public GameObject prefabBox;

    GameObject box1, box2;

    private void Start()
    {
        box1 = Instantiate(prefabBox);
        box1.transform.position = new Vector3(1, 2, 3);
        Debug.Log(box1.GetComponent<Collider>().bounds); //Prints the value of the box in its prefab position

        box2 = Instantiate(prefabBox);
        box2.transform.position = new Vector3(4,5,6);
        Debug.Log(box2.GetComponent<Collider>().bounds);//Prints the value of the box in its prefab position
    }

    private void OnGUI()
    {
        if (GUILayout.Button("Check bounds now")) //Physics will have been updated by the time you can click this
        {
            Debug.Log(box1.GetComponent<Collider>().bounds); //Now shows the bounds at position 1,2,3

            box2.transform.position = new Vector3(10, 10, 10); //Move box2
            Debug.Log(box2.GetComponent<Collider>().bounds); //Shows wrong bounds from position 4,5,6
        }
    }

A solution to the problem for newly instantiated prefabs is to use the Instantiate overload with position,
eg: box1 = Instantiate(prefabBox, new Vector3(1,2,3), Quaternion.identity);
But if you move the GameObject, you MUST wait for a physics update before the bounds are accurate.

2 Likes

You can change this by setting Physics.autoSyncTransforms to true, and you can work around it in a single instance by calling Physics.SyncTransforms().

Note that both have overhead. As you can see from the documentation in Physics.autoSyncTransforms, before 2017.2, this wasn’t an issue, but that did cause Unity games to run a lot slower if physics objects were moved a lot.

6 Likes

Cool!

Wow,

This solved my issue!

Thanks,
jrDev