I am trying to implement a simple script to drag a GameObject with the mouse in Unity. However, when the position of the object is updated with the following script, I get an error saying:

transform.position assign attempt for 'purpie_5' is not valid. Input position is { Infinity, 51351759646418134000000000000000.000000, -143589927261340110000000000000000000000.000000 }.

I am not sure what I am doing wrong. This is the code I am using:

public class MouseInputInterface : MonoBehaviour {

public Transform heldObject;
#endregion //PUBLIC MEMBERS

private GameObject currTarget;
private Vector3 touchOffset;
private bool dragging = false;
#endregion //PRIVATE MEMBERS

// Use this for initialization
void Start () 


    void Update()
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        if(Physics.Raycast(ray,out rHit))

            currTarget = rHit.transform.gameObject;

            if(currTarget != null)
                if(!dragging && currTarget.transform.tag == "Moveable")
                    dragging = true;
                    heldObject = currTarget.transform;



        if(heldObject != null)
            /*calculate offset*/
            Vector3 screenPoint = Camera.main.WorldToScreenPoint(heldObject.position);

            /*calculate offset from camera*/
            Vector3 offset = heldObject.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));

            //form the current position
            Vector3 curPosition = Camera.main.ScreenToWorldPoint(screenPoint) + offset;

            heldObject.transform.position = curPosition;
    else if(Input.GetMouseButtonUp(0))
        //clear held object
        heldObject = null;
        //clear flag
        dragging = false;


Thanks for the help.

| improve this question | | | | |

In the line where you get the world position of the mouse:

    new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));

The z value should be the difference from the camera to the object. For example, with a camera looking "down" the Y axis:

public Vector3 GetMousePositionInWorld(Transform heldObject) {
    Vector3 clickPos = Input.mousePosition;
    clickPos.z = Camera.main.transform.position.y - heldObject.position.y;
    Vector3 mousePositionInWorld = Camera.mainCamera.ScreenToWorldPoint(clickPos);

    //You may want to set the position again to clean up floating point errors
    mousePositionInWorld.y = heldObject.position.y;

    return mousePositionInWorld;
| improve this answer | | | | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.