Search Unity

MeshRenderer has wrong bounds when rotated

Discussion in 'Scripting' started by Koval331, Aug 29, 2019.

  1. Koval331

    Koval331

    Joined:
    Feb 3, 2019
    Posts:
    114
    Hi. When I try to get the bounds of my models (created in Blender) and show them in Inspector:

    upload_2019-8-29_16-55-36.png

    As you can see the bounds are correct when the objects are not rotated. But when they are (left-most object) bounds start getting totally wrong.

    Here is a script that shows / gets the bounds:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class GetBounds : MonoBehaviour
    6. {
    7.     public MeshRenderer mesh_renderer = null;
    8.  
    9.     public bool show_bounds = false;
    10.  
    11.     private void OnDrawGizmos()
    12.     {
    13.         if (!show_bounds) return;
    14.  
    15.         Gizmos.DrawWireCube(mesh_renderer.bounds.center, mesh_renderer.bounds.size);
    16.         Gizmos.DrawWireSphere(mesh_renderer.bounds.center, 0.3f);
    17.     }
    18. }
    How can I fix this?
     

    Attached Files:

  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,748
    From this documentation:

    https://docs.unity3d.com/ScriptReference/Mesh-bounds.html

    It seems they bounds-box it in local space, then if you have rotated the transform, they recompute bounds at the new world-aligned axis around that local box, but it isn't really specified explicitly. Anything not explicitly promised in an API is dangerous to rely upon for future functionality, so it might be you need to compute your own bounds if it is that critical to your app functionality.

    You can do your own bounds computation as there are plenty of open source examples out there, and it is trivially easy to pluck vertex information out of a Unity3D MeshFilter's mesh.
     
    Koval331 likes this.