Moving Object At MousePosition.X


i’m Trying to Make a CrossHair But Not As Texture,
i’m Making it as Gameobject

but i got problem in making it follow the mouse

public GameObject CrossHair;

//Start Void

	CrossHair = Instantiate(CrossHair,transform.position,transform.rotation) as GameObject;

//Update Void

	CrossHair.transform.position.x =(Camera.main.ScreenToWorldPoint(Input.mousePosition).x);

what is the wrong in this code

Does this code compile? The big issues is that ScreenToWorldPoint() takes a Z parameter that is the distance into the scene to place the object. I’ll assume you don’t want the Z value to change for your crosshair object. This assumes you are looking down the Z axis. This can be written more compactly (less steps), but for the sake of understanding:

Vector3 v3Pos = Input.mousePosition;
// Set 'Z' to the distance in front of the camera;
v3Pos.z = Mathf.Abs(CrossHair.transform.position.z - Camera.main.transform.position.z);
v3Pos = Camera.main.ScreenToWorldPoint(v3Pos);
v3Pos.y = CrossHair.transform.position.y;
CrossHair.transform.position = v3Pos;