Search code examples
c#scalaunity-game-enginecameragameobject

Unity3D: Convert all game objects to same size irrespective of it's scale


Suppose I have a reference GameObject, Cube, with scale (1,1,1). There is another GameObject with scale (1,1,1), but the size is 3 times bigger than the Cube. How do I dynamically change the scale of the Game objects to fit the size of the Cube?


Solution

  • Get the mesh filter on each and use Mesh.bounds.size to get their sizes. To make the second object fit inside the first, you'd change the second object's scale based on the different in mesh size.

    // If you want it to be 100% accurate, you should multiply RefSize here 
    // by RefMeshFilter.transform.lossyScale so that the other object's 
    // size also accounts for the reference object's scale.
    var RefSize = RefMeshFilter.bounds.size;
    var MySize = MyMeshFilter.bounds.size;  
    var NewScale = new Vector3(RefSize.x / MySize.x, RefSize.y / MySize.y, RefSize.z / MySize.z);
    
    // I'm un-parenting and re-parenting here as a quick way of setting global/lossy scale
    var Parent = MyMeshFilter.transform.parent;
    MyMeshFilter.transform.parent = null;
    MyMeshFilter.transform.localScale = NewScale;
    MyMeshFilter.transform.parent = Parent;