So I know this is probably a question with a super easy fix, but I am tired of trying to figure it out. I am trying to cast a ray from the mouse, which I have succeeded in doing (I am very new to raycast!) but for some reason, even though this fix worked for someone else, It does not work for me.
The code:
#pragma strict
function Update () {
if (Input.GetButtonDown ("Fire1")) {
// Construct a ray from the current mouse coordinates
var hit : RaycastHit;
var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray)) {
if (hit.collider.tag == "TestBlock")
{
Debug.Log("RaycastWorks");
}
}
}
}
I am getting the error of: NullReferenceException: Object reference not set to an instance of an object
#pragma strict
function Update () {
if (Input.GetButtonDown ("Fire1")) {
// Construct a ray from the current mouse coordinates
var hit : RaycastHit;
var distance : float = 100;
var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, hit , distance)) {
if (hit.collider.tag == "TestBlock")
{
Debug.Log("RaycastWorks");
}
}
}
}
The problem with your previous code was that you are trying to get the tag of the object hit by the raycast but the fact that
it was empty caused an error ( NullErrorException ) . Simply fix this by using the correct overload for Physics Raycast that asks for a RaycastHit parameter with the other parameters you wanted. I have provided the solution as stated above. Hope it helps.