Trying to move an object to Mouse x and z positions only?

Hi, I’m trying to move an object in the game to the Mouse x and z coordinates whenever I right-click, but not to the Y coordinate. Here is my code:

using UnityEngine;
using System.Collections;

public class Mousetargeting : MonoBehaviour
{	void Update ()
	{
		if(Input.GetMouseButtonDown(1))
		{
			transform.position = new Vector3(mousePosition.x, -.45, mousePosition.z);
		}
	}
}

I’m not sure how to just call up the mouse X and Z coordinates when I’m transforming the position. Help?

Your question lacks details for a solid answer. While Input.mousePosition is a Vector3, the ‘z’ is 0.0, so there is no inherit ‘z’ to mousePosition. Depending on the rotation of the camera and the nature of the game, there are a variety of ways of placing an object in the scene. As @KevLoughrey mentions, you can use Camera.ScreenToWorldPoint(). If we assume the rotation of the camera is (0,0,0) with your object in front of the camera, then the ‘z’ position will be at some specific distance in front of the camera. So your code might look like:

void Update ()
{
   if(Input.GetMouseButtonDown(1))
   {
       float dist = transform.position.z - Camera.main.transform.position.z;
       Vector3 pos = Input.mousePosition;
       pos.z = dist;
       pos = Camera.main.ScreenToWorldPoint(pos);
       pos.y = transform.position.y;
       transform.position = pos;
   }
}

So we first calculate the distance between our object and the camera on the ‘z’ axis. Then we create a Vector3 composed of the mousePosition and the distance as the ‘z’ component. ScreenToWorldPoint() converts that Vector3 into a world position. Since you did not want the ‘y’ component, we overwrite the ‘y’ component with the current one of the object, and finally assign the result to ‘transform.position’.

Input.mousePosition