Snap to place

i am trying to make it so that if an object that im dragging around gets close to any empty Gameobject with the name “TopSnap” then it will move to the top of the object and if it gets close to anything names “BottomSnap” then it will move to the bottom. I will have a few cylinders with 2 empty game objects on it one will be the top snap and the other is the bottom snap.

If you are using rigidbodies, you can create triggers in your empty gameobjects to represent the area in which the object will snap. Then add a script to them with the OnTriggerEnter function, in which make the position of the object which enters the trigger same as the empty gameobject in which it entered. Or if you are not using rigidbodies, each update check the sqrdistance between each object and the topsnap or bottomsnap gameobjects. If it is less than a certain value, then snap the object. Personally I prefer the first method, with kinetic rigidbodies and using rigidbody.MovePosition(). It is easier to implement and involves just half a dozen lines of code.

EDIT: Steps for first method:

  1. Add any tag to your cylinders or gameObjects which you want to snap

  2. Add a box collider or sphere collider to both TopSnap and BottomSnap objects, resize it to depict the area in which the object, on entering will be snapped. This can be any size you like.

  3. Add rigidbodies to all gameObjects you want to snap and make sure they have a collider (collider should be on same transform as rigidbody).

  4. Create a new script and add the following code to it:

    void OnTriggerEnter(Collider other) {
    if(other.gameObject.CompareTag(“the_tag_which_you_kept_earlier”) {
    other.rigidbody.MovePosition(transform.position);
    }
    }

  5. Attach the script to the TopSnap and BottomSnap gameObjects

  6. Done!