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.