Drag GameObject only in a specific area

Hi there!

I’m kinda new to Unity (but used to programming with javascript) and got the following problem:

I want to use a interactive tool where the user can operate technical devices via drag and drop. For example grabbing a robot arm and dragging it along its rail (Dragging is needed, can’t use GUI Elements).

I found billions of scripts for dragging around GameObjects in Unity but the following problems remains and I really hope some got a easy solution:

  • I need to choose whether the object can be moved on X-Axis, Y-Axis or both
  • The object “jumps” to where the cursor is pointing when it’s clicked
  • The object must only be moved along it’s rail, so how far I can drag it must me limited somehow.

Additional Information: The script is implemented into my main camera and the objects which are able to be dragged are selected via a “dragable”-tag.

Sorry for asking such basic stuff but I’d be really grateful for anyone to help me!


  • Create an enum and check it when you
    move. If it’s Y_only, for instance,
    then do newPos.x = oldPos.x;
  • When you
    click on a collider, you can get the
    impact point ray / collider. You just
    have to set the position of the
    object to that point.
  • For the last
    one, I suggest you find/write a
    function that gives you the closest
    image of a point on a line, then
    create a line (your rail) and finally
    affect that point to the transform
    each frame.