Trying to create script that drags an object connected by a hinge

So, I am trying to write a script where an object at the end of a chain of hinges follows the mouse. The problem is that when I use seemingly anything that involves “transform.position = …”, the object I am trying to drag completely disconnects from the chain. So is there anything I can do to make this work?

Here is my code:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class FollowMouse : MonoBehaviour
 {
     void Update()
     {  
         float xMousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition).x;
         float yMousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition).y;
         new Vector3 mousePos = (xMousePos, yMousePos, 0)
         transform.position = Vector3(xMousePos, yMousePos, 0);
     }
 }

I have tried other things, but this is essentially what I have been doing. Thanks.

An object whose position is managed by the physics simulation (it hangs off of its hinges) is what’s called a dynamic rigidbody, and you should NEVER try to move those through their transform.position.

Dynamic rigidbodies should only be moved through the physics simulation (e.g.: applying forces to their rigidbody).

The simplest and possibly best solution for you is to NOT move the FollowMouse object itself, but to move ANOTHER object FollowMouseTarget without a rigidbody. Then you simply add a spring joint connecting your FollowMouse object to the FollowMouseTarget object.

Physics joints may still break or behave erratically if you pull too far, but the construct will work perfectly fine if configured correctly.