snap object to another object

how do I snap Cube1 to Cube2 when they are very close to each other? can it be used with rigidbody objects? grateful if anyone could help in c#

If these objects are simple cubes with all the same size, you first need to check whether or not the distance between the two objects is < some value. You can achieve this with Vector3.Distance.

so something with this structure

if(Vector3.Distance < 5.0f) snap

Then you want the objects to snap, this is a bit more tricky. With simple cubes, you could try this logic:

if the distance between the two cubes is small enough
→ cube2.position.x = cube1.position.x + cube1.localscale.x
→ cube2.position.y = cube1.position.y
→ cube2.position.z = cube.position.z

OR

look at this tutorial

http://catlikecoding.com/unity/tutorials/frames-per-second/

where they also make some objects snap to one another

How to snapping 2D Ui to another 2D Ui when they ar very near to each other?125558-snapping.gif