Trying to make gameobject follow mouse cursor. It disappears instead.

So, after a long time of not flexing any sort of programming/ game-dev mucle, I decided that today I would try to make a very simple game in Unity to warm myself up a little inside.

Problem is, I am trying to do something very simple, with the simple script below, and it is not working. Also I do not know why.

The following is a monobehavior script in C#  placed on a sprie game object. Which is currently the only game object on screen.

using UnityEngine;
using System.Collections;

public class FollowMouseScript : MonoBehaviour {
	public Vector3 UltimatePosition = new Vector3(0,0,0);
	float X, Y;



	// Use this for initialization
	void Start () {

	
	}
	
	// Update is called once per frame
	void Update () {

		X = Input.mousePosition.x;
		Y = Input.mousePosition.y;
		Vector3 mouselocation = Camera.main.camera.ScreenToWorldPoint(Input.mousePosition);
		transform.position = mouselocation;
		//print("MouseX: " + X + " MouseY: " + Y);

		//print(transform.position.x + "," + transform.position.y + "," + transform.position.z);
		if (Input.GetMouseButtonDown(0) || Input.GetMouseButtonDown(1)  == true) {
			print("click");
				}

	}
}

The problem is, both of my print statements to the console tell me that the transform.position(s) of the object are being properly set. However, the object appears to just disappear. I have checked the z values of the camera and the object (I’m working in 2D mode) and the camera defaults to -5 and the sprite defaults to 0).

Any suggestions/help?

EDIT: Upon some further reading and some editing, I have now accounted for the difference in screenspace and world space using Camera.main.camera.ScreenToWorldPoint. The issue remains. I can post my altered code if you guys wish.

Yes, edit your question and replace your code above with the latest. Note when setting up the position you will pass to ScreenToWorldPoint(), the ‘z’ must be set to the distance in front of the camera. Your code here is setting it to transform.position.z. For a camera without rotation and moving objects parallel to the camera plane, you can calculate the ‘z’ paramter as:

Vector3 pos = Input.mousePosition;
pos.z = transform.position.z - Camera.main.transform.position.z;
transform.position = Camera.main.ScreenToWorldPoint(pos);

Thanks for posting these replies. It really helped me out.

@bls61793 Although this thread is pretty old, I wasn’t sure if you got the answer your question about why you can’t see your sprites when the camera z is set to 0. In case you haven’t and you come back to this for whatever reason, the answer is because with the camera and sprite being on the same z plane, if both are set to 0, the camera is too close to see the sprite. You add the distance of 10 to push the camera further back from the sprite which is why you are now able to see it.

Thanks again!