How can I make a gameobject snap to something when it gets close to it?

Any idea if there is a way I can make a gameobject snap to something when it gets close to it? Like drag a cube around and when it gets close to something then snap to it.

• I upvoted it to counter the downvote, because I tried searching, and it took a while to find anything, as snapping defaults to result for snapping in the scene editor, after about 5 or 6 tries, I still only found weak unclear references. Nov 17, 2017 at 18:20

Any position you want it to snap to as it gets close, you could do something like this (Psuedo code)

(assuming you already have code to move the object) - Create a parent object, that contains the script SnapOn.
- That parent object is what moves.
- The child object should have the visible element, cube for instance. - In the SnapOn Script, - - The anchors are used to define positions the object can snap to - - The "movable" is the child object that actually renders. - - SnapDistance is how far away to snap.

class SnapOn {
public Transform[] anchors;
public Transform movable;
public float SnapDistance = 1f;

Update() {
// first we find the closest object, but looping through all and saving the shortest distance (and position)
var distance = float.max;
var point = vector3.zero;
foreach(var anchor in anchors)
{
var d = Vector3.Distance(transform.position, anchor.position);
if (d < distance)
{
distance = d;
point = anchor.position;
}
}

// now we decide if there is anything it should snap to.
if (distance > SnapDistance) // too far, keep renderable with movable.
{
movable.position = transform.position;
}
else // position is close enough to snap point put it there.
{
movable.position = point;
}
}


if you neglect to track the moving position separate from where to render the object, the instance you are on a snap on to a position, you will unlikely be able to move the object far enough in a single frame to allow it to "unsnap"