Object follow Cursor - How to access mouse cursor x and y position

I have looked this question up and found plenty of answers, only every answer is code with errors, or it just plain didn’t work. Here is what I have written myself which works (C#):

void Update () {
		this.transform.position = Input.mousePosition;
	}

BUT this positions the object out of my camera view.

If I try to access the y or x coordinate alone I get errors.

“Cannot modify a value type return value of ‘UnityEngine.Transform.position’. Consider storing the value in a temporary variable”

If I try storing these values in a variable I get

“Unexpected symbol `=’ in class, struct, or interface member declaration”

What is the proper way of doing this? Thanks

I doubt that this.transform.position = Input.mousePosition; is really what you want. transform.position is measured in world units in 3d space. mousePosition is in pixel units in 2d space, so mapping one directly to the other makes little sense. Instead, you need to use the ScreenToWorldPoint method.

Something like this (untested):

void Update () {
  Vector3 temp = Input.mousePosition;
  temp.z = 10f; // Set this to be the distance you want the object to be placed in front of the camera.
  this.transform.position = Camera.main.ScreenToWorldPoint(temp);
}

Try this for mousePosition:

Vector2 mousePosition = new Vector2 (Camera.main.ScreenToWorldPoint (Input.mousePosition).x, Camera.main.ScreenToWorldPoint (Input.mousePosition).y);