Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

PSA: Collider Bounds Incorrect Until Phyiscs Update

Discussion in 'Scripting' started by hpjohn, Apr 8, 2019.

  1. hpjohn

    hpjohn

    Joined:
    Aug 14, 2012
    Posts:
    2,190
    Collider.bounds "The world space bounding volume of the collider"
    https://docs.unity3d.com/ScriptReference/Collider-bounds.html

    But the value is wrong if you move a GameObject and then query the bounds in the same frame.
    Code (CSharp):
    1.     public GameObject prefabBox;
    2.  
    3.     GameObject box1, box2;
    4.  
    5.     private void Start()
    6.     {
    7.         box1 = Instantiate(prefabBox);
    8.         box1.transform.position = new Vector3(1, 2, 3);
    9.         Debug.Log(box1.GetComponent<Collider>().bounds); //Prints the value of the box in its prefab position
    10.  
    11.         box2 = Instantiate(prefabBox);
    12.         box2.transform.position = new Vector3(4,5,6);
    13.         Debug.Log(box2.GetComponent<Collider>().bounds);//Prints the value of the box in its prefab position
    14.     }
    15.  
    16.     private void OnGUI()
    17.     {
    18.         if (GUILayout.Button("Check bounds now")) //Physics will have been updated by the time you can click this
    19.         {
    20.             Debug.Log(box1.GetComponent<Collider>().bounds); //Now shows the bounds at position 1,2,3
    21.  
    22.             box2.transform.position = new Vector3(10, 10, 10); //Move box2
    23.             Debug.Log(box2.GetComponent<Collider>().bounds); //Shows wrong bounds from position 4,5,6
    24.         }
    25.     }
    26.  
    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. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,294
    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.
     
  3. hpjohn

    hpjohn

    Joined:
    Aug 14, 2012
    Posts:
    2,190
    Cool!
     
  4. crafTDev

    crafTDev

    Joined:
    Nov 5, 2008
    Posts:
    1,820
    Wow,

    This solved my issue!

    Thanks,
    jrDev