- Home /
Question by
teunissenstefan · Oct 30, 2014 at 05:54 PM ·
mouseposition
Object reference not set to an instance of an object Camera.main.ScreenPointToRay (Input.mousePosition)
This has been asked before, I have seen it, but none of those answers could help me.
With the code below I get the following error: Object reference not set to an instance of an object (line 9) The error is on var ray = Camera.main.ScreenPointToRay (Input.mousePosition); When I debug Input.mousePosition the Z is always 0.0. Is that the problem? Or how do I fix it?
#pragma strict
var speed : float = 20.0;
var move : boolean;
var wantedPosition : Vector3;
function Update () {
if ( Input.GetMouseButtonDown ( 0 ) ) {
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
if ( Physics.Raycast (ray, hit) ) {
move = true;
wantedPosition = hit.point + Vector3 ( 0.0, 30.0, 0.0 );
}
}
if ( move ) {
transform.LookAt ( wantedPosition );
transform.Translate ( Vector3.forward * Time.deltaTime * speed );
if ( Vector3.Distance ( transform.position, wantedPosition ) < 0.01 ) {
move = false;
}
}
}
Did I do something wrong? I just followed a tutorial.
Comment
Best Answer
Answer by robertbu · Oct 30, 2014 at 05:54 PM
This problem is likely because you've changed the tag on your camera. The use of 'Camera.main' depends on the camera having the tag 'MainCamera'.