- Home /
The question is answered, right answer was accepted
Finding a RaycastHit tag (Null Reference Exception)
So I've searched around for about 2 days and I've been unable to fix this issue I've been having. Wherein, I receive a Null Reference Exception when I try to check the tag of a raycast hit target on the ground. Here's a brief explanation of what I'm trying to do.
var hit : RaycastHit;
function Update() {
Debug.DrawRay (transform.position, transform.forward * 10, Color.green);
if (Physics.Raycast (transform.position, transform.forward, 10)) {
if(hit.collider.tag == "Pickup"){
print("Pickup!");
}
else{
return hit;
}
}
}
So essentially, my raycast is labeled here by the green Debug.DrawRay. The raycast shoots from the center of my flashlight beam and attempts to detect any items with the tag "Pickup" within a distance of 10 units from the player. However, when I attempt to ask about the tag using an if statement, I am uncertain what to use in order to ask the proper question. hit.collider.gameObject.tag or hit.collider.tag. I've also tried hit.transform.gameObject.tag and hit.transform.tag. All of which give me the same error. Which begs the question, am I missing something or am I going about this entirely wrong?
NullReferenceException: Object reference not set to an instance of an object
pickup_objects.Update () (at Assets/pickup_objects.js:4)
Answer by kromenak · Jul 02, 2015 at 06:48 PM
I think the core issue is that you are never actually assigning the "hit" variable. You need to use one of the versions of Physics.Raycast that returns the RaycastHit variable when it hits something. If you don't do that, you'll always get a NullReferenceException, because your variable "hit" will always be null.
As for the correct variable to use from the RaycastHit class, "collider" or "transform" or "gameObject" would be fine.
I got it! $$anonymous$$y issue was replacing the "10" in my raycast with "hit." I thought that location was solely for the length of the raycast, so I never thought to define the RaycastHit there. Thank you!
You need to read the raycast page in the scripting api. It shows how you can mix and match any arguments you need. You shouldnt need to replace anything, just add the extra info in, in the correct order for the given variation.
Answer by Ibzy · Jul 02, 2015 at 06:54 PM
It looks like you're missing the "out hit" parameter from your raycast. Without it, your hit variable remains empty.