- Home /
Need some help with JS raycasting hitting a certain tagged object
I am having problems with my raycast code in JS sending back a null ref. error every time I check to see if it hit the door object tagged "door". The raycaster is in front of my FPController, and I'm needing to check if I'm in front of the door when I press the c key. If I am in front of door within specified range, allow me to open door with another key. If not, I can't open door. Hope this makes sense and I can get some help here. Thanks in advance.
#pragma strict
var raycastDist: float = 2.0;
function Update ()
{
var hit: RaycastHit;
Debug.DrawRay (transform.position, transform.forward, Color.green);
if(Input.GetKeyDown("c"))
{
if(Physics.Raycast(transform.position, transform.forward, raycastDist))
{
if(hit.collider.gameObject.tag == "door")
{
print("hit door detected");
}
}
else
{
print("no hit door detected");
}
}
}
I'm not sure why you're getting a NullRef, but I'd just like to point out that you've set up your print functions incorrectly. Right now your program will print "no hit door detected" if your raycast doesn't hit anything, not if it hits something and that isn't the door. If I'm not mistaken you want something along the lines of this
if (Physics.Raycast(transform.position, transform.forward, raycastDist))
{
if (hit.collider.gameObject.tag == "door")
{
print("hit door detected");
}
else
{
print("no hit door detected");
}
}
Answer by robertbu · Apr 13, 2014 at 06:45 AM
You are not passing your RaycastHit structure into your Raycast() function, so even when the Raycast succeeds, the 'hit' variable is not initialized. You need to call it this way:
if (Physics.Raycast(transform.position, transform.forward, hit, raycastDist))
The signature of the call you want to make is:
static function Raycast(origin: Vector3, direction: Vector3, hitInfo: RaycastHit, distance: float = Mathf.Infinity, layerMask: int = DefaultRaycastLayers): bool;
Your answer
Follow this Question
Related Questions
Clicking multiple objects with same tag, how to "forget" the one clicked previously... 0 Answers
find tag from raycast 1 Answer
Finding a RaycastHit tag (Null Reference Exception) 2 Answers
Comparing tag not working 0 Answers
Raycast ignore player 3 Answers