- Home /
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;NullReferenceException
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. Thanks!
Thanks, it wasn't the result i expected to have, but it is surely the solution for this problem. :)
EDIT: how to make your answer the solution for my issue?
Answer by weltraumaffe · Aug 28, 2013 at 10:09 PM
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.
Your answer
Follow this Question
Related Questions
Trying To Find Mouse Position On Tap 1 Answer
collider2D.bounds.Contains not working properly 3 Answers
ScreenToWorldPoint and Mouse Position 2 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers