Convert Mouse Position to move a cube on 1-axis.

Hello! This is my post here, and first of all i must say that i’m really at a starting point on C# scripting and Unity…

What i want to do it, using iTween Plugin, move a cube on y-axis at the same screen height of mouse click.

The error i’m getting is

UnityEngine.Camera.WorldToScreenPoint (Vector3 position)
Cube.Update () (at Assets/Cube.cs:17)

The code i’m using, attached to Cube object, is:

using UnityEngine;
using System.Collections;

public class Cube : MonoBehaviour {
	private Vector3 mousePos;
	void Start () {
	void Update () {
		if (Input.GetMouseButtonDown(0))
		Vector3 mousePos = Camera.main.WorldToScreenPoint(Input.mousePosition);
		gameObject.MoveTo (new Vector3 (0,mousePos.y,0), 3, 1);

Sorry if i made a mess, but i’m trying to learn basis to make a simple 2d game. If someone could gently help me to understand (not fix only the code ^^) it would be really nice.


Could you check in the Hierarchy if the Camera has the MainCamera tag attached to it? If not then Camera.main is not set (null)

You should use ScreenToWorldPoint, you want to convert a position from screen space to world space not the other way around.