Wrote a script to pick up objects detected by raycast, but they are dropping unexpectedly.

The camera in my scene is stationary, and I want to be able to pick up objects that spawn and move them by dragging them with the mouse. It is working for the most part, except that the objects randomly drop while the mouse button is still being held.

{
    public Camera gameCamera;

    void Update()
    {
        Ray ray = gameCamera.ScreenPointToRay(Input.mousePosition);
        RaycastHit hitInfo;

        if (Physics.Raycast(ray, out hitInfo) && Input.GetMouseButton(0) && hitInfo.collider.gameObject.CompareTag("MoveableObject"))
        {
            hitInfo.collider.gameObject.transform.position = gameCamera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 8));
        }
    }
}

Here is what it looks like when playing:
193076-unity-pickupobject.gif

The issue is that you are moving the mouse too fast, so for a frame, the raycast no longer hits the box, and you drop it. An easier way to solve this is to create a script and attach it to the GameObjects you want to move. Using Unity’s OnMouseDown and OnMouseUp, we can “select” the object without the need for a raycast.

using UnityEngine;

public class MoveableObject : MonoBehaviour
{
    private bool objectSelected;

    private void OnMouseDown()
    {
        objectSelected = true;
    }

    private void OnMouseUp()
    {
        objectSelected = false;
    }

    void Update()
    {
        if (objectSelected)
        {
            transform.position = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 8));
        }
    }
}