how to make a game object follow the mouse cursor

How do I get it to where I make a game object stays under the cursor. No other answers are clear so please help.

edit: I also want to know if it could be in a grid like area so instead of being free move, it snaps

There’s many approaches to how you want to do this, and it all depends on what you want to achieve. You can make your object follow your mouse without depending on a Z coordinate, and you could also have your object be aligned to another object (such as a ground), if the mouse is over that object.

  • First method

You can use Camera.main.ScreenToWorldPoint(Input.MousePosition) to get your mouse position in world space as a Vector3. Instead of using that exactly, try using this:

float zAxis = 2f;
Vector3 mousePosition;

void Update() {
    mousePosition = Camera.main.ScreenToWorldPoint(Input.MousePosition);
    mousePosition.z = zAxis;
    //If you get an error with the above line, replace it with this:
    //mousePosition = new Vector3(mousePosition.x, mousePosition.y, zAxis);


When you use ScreenToWorldPoint to get mouse position, the Z axis will either be really strange, or 0.

You can then use the Vector3 mousePosition to set the transform.position of another object to where the mouse cursor is in world space.

  • Second Method

If you have a floor in your scene, you could also raycast from your mouse cursor to plant your object on the ground.

Try using this code to achieve this:

RaycastHit hit;
Ray ray;

void Update() {

    ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    if(Physics.Raycast(ray, hit, Mathf.Infinity) {
        transform.position = hit.point;


You can place this code on an object to make it align to the mouse when the mouse is over any object.
This is untested, so I’m unsure of any errors. Also keep in mind that any object will be placed on your ground at the center/pivot point; For example, Unity’s primitive cube will be halfway into the ground.