Thursday, January 23, 2014

Unity 3D: Awwww, Snap!

These aren't brand new techniques, but they weren't in Unity from the outset, so even some veterans seem to be unfamiliar with them. Unity is able to snap objects to a custom grid, or to one another.

To snap to a custom grid, you can first set up the size of the grid by going to "Edit > Snap Settings." Let's say I have a prefab at a size of (0.5f, 1f, 0.5f), and I want to snap a bunch of instances together on the X and Z axes. I can just set the "Move X" and "Move Y" values to 0.5, and I know that every snap step is exactly one object unit in either direction.

To actually snap, just grab an object and move it while holding Ctrl in Windows or Cmd on Mac. Now, the object will move by the amount you designated in "Snap Settings."

Snapping meshes together is even simpler: just hold Shift + Ctrl or Shift + Cmd and drag an object around by its center. Note that the objects being snapped together both need to have colliders.

Finally, you can snap objects together by vertices. This one's a little more involved but it's great for attaching dissimilar, oddly-shaped or -sized objects. Taken directly from Unity's "Positioning GameObjects" page:

Vertex Snapping
  • Select the mesh you want to manipulate and make sure the Transform Tool is active.
  • Press and hold the V key to activate the vertex snapping mode.
  • Move your cursor over the vertex on your mesh that you want to use as the pivot point.
  • Hold down the left button once your cursor is over the desired vertex and drag your mesh next to any other vertex on another mesh.
  • Release your mouse button and the V key when you are happy with the results.
  • Shift-V acts as a toggle of this functionality.
  • You can snap vertex to vertex, vertex to surface and pivot to vertex.