- Home /
render the bounding box of collider or mesh how to?
i want to figure out how to draw the bounding box of the mesh or collider that is attached to the mesh. i dont know what to use, bounding box of the mesh, collider or renderer? my goal is to get the position of all vertices making the bounding box and then render the lines between so that i can get wireframe cube, this way it will be easy to determine what object is selected in the scene.
is there a easy way to do this? and how to get the vertices. i can get the center of the bounding box like this:
Debug.Log(transformTemp.collider.bounds.center.ToString());
thanks!
Answer by QuantumRyan · Jun 29, 2011 at 09:09 PM
I do something like this in a script attached to the GameObject. It allows me to use the in scene Gizmo's toggle, as well as my own selection options (like mouse click). (This only applies in the unity Game and Scene windows FYI.)
public bool _bIsSelected = true;
void OnDrawGizmos()
{
if (_bIsSelected)
OnDrawGizmosSelected();
}
void OnDrawGizmosSelected()
{
Gizmos.color = Color.yellow;
Gizmos.DrawSphere(transform.position, 0.1f); //center sphere
if (transform.renderer != null)
Gizmos.DrawWireCube(transform.position, transform.renderer.bounds.size);
}
The above script works fine, but I noticed more accurate results when ins$$anonymous$$d of using transform.position in "Gizmos.DrawWireCube(transform.position, transform.renderer.bounds.size);" I use transform.renderer.bounds.center
The documentation even says renderer.bounds.center is more precise http://docs.unity3d.com/ScriptReference/Renderer-bounds.html
edit - although using renderer.bounds.center do accurately show the bounding box covering all of the mesh, When doing calculations in regard to the collider, then using the renderer wont be accurate. So Ins$$anonymous$$d use collider.bounds.center and collider.bounds.size
(side note - I don't really like how every little edit I do bumps the thread in unity answers)
Answer by ga5p0d3 · Nov 19, 2019 at 10:05 AM
Here's my version, which ensures all (self and) child meshes have their bounds drawn and the full object/sub-object transform is used to draw each bounding box.
void OnDrawGizmosSelected()
{
Gizmos.color = Color.magenta;
foreach(var mf in GetComponentsInChildren<MeshFilter>())
{
Gizmos.matrix = mf.transform.localToWorldMatrix;
Mesh m = mf.sharedMesh;
Gizmos.DrawWireCube( m.bounds.center, m.bounds.size );
}
}