This question was
closed Jan 10, 2016 at 01:50 PM by
AnniJ for the following reason:
The question is answered, right answer was accepted
Question by
AnniJ · Jan 09, 2016 at 06:02 PM ·
c#nullreferenceexceptiontagraycasthit
NullReferenceException when trying to find tags with RaycastHit
Hey guys,
it's all in the title ;) I have a short script and the only thing I'd like to do is finding out weather certain objects have the tag "item" on them, but I always get the "NullReferenceException" Error when I click.
What am I doing wrong? Help!
using UnityEngine;
using System.Collections;
public class Pickup : MonoBehaviour {
void Update (){
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Input.GetMouseButtonUp(0) && Physics.Raycast(ray, 100)) {
if (hit.collider.gameObject.tag == "item")
{
print("Hit something");
}
}
}
}
Comment
Best Answer
Answer by DCordoba · Jan 09, 2016 at 09:38 PM
you not initialize variable hit, use some like
if (Input.GetMouseButtonUp(0) && Physics.Raycast(ray, out hit)) {