How to align the bottom of a GameObject with the ground?

Hello!

I’m creating a simple strategy game and I use a Raycast to determine the location that the selected unit(s) should be moved to. I wonder how I can align the bottom of each unit with the ground, because if I move the object to the location of the hit, it is being placed in the ground.
I have tried adding half of the object height ( transform.localScale.y / 2 ) to the Y coordinate, but it doesn’t really work.

All help is appreciated!

// TheDDestroyer12

Hi, it depends where is the “pivot” of your object. The pivot is the local (0,0,0) of the object but it can be anywhere depending on the geometry + the object’s scaling, rotation etc… You can visualize the pivot by selecting an object and selecting “pivot” instead of “center” in the upper left corner of Unity’s window (under the menu)

Now, there is also a property of a mesh that can help you: the bounds. At import time, Unity will compute an axis aligned bounding box that will contain all vertices of the mesh. Just in case, you can ask to recompute it in the Start() of a component for example.

To acces the bound: use GetComponent to get the MeshFilter component and use meshfilter.sharedMesh (using meshfilter.mesh could duplicate the mesh and make it unique for your object, you don’t want that)

Now, you have a variable “Bounds b” that contains the mesh bounding box. You can now have access to the center of the object with b.center, and to the height of the object with b.extends.y * 2. So, the center of the box on the “ground” will be at Vector3 lowerCenter = b.center + Vector3( 0, -b.extends.y, 0) in object space. I assume that you don’t have rotations around X or Z (around Y would not change anything) but you may have scaling. Then, just multiply b.extends.y by transform.localScale.y before adding the result to b.center to compute lowerCenter.

To position the object on the ground at, say, Vector3 pos, set the transform.position = pos - lowerCenter;