- Home /
Raycasting and Tag Checking in C#?
Can anyone tell me what's wrong with this script?
using UnityEngine;
using System.Collections;
public class pickUp : MonoBehaviour
{
public float distance = 1f;
void Update()
{
Vector3 fwd = transform.TransformDirection(Vector3.forward);
RaycastHit hit;
if (Physics.Raycast(transform.position, fwd, distance) && hit.transform.tag == "Baby")
{
print("Something is a baby in front of the player?");
}
}
}
I'm getting this error: NullReferenceException: Object reference not set to an instance of an object pickUp.Update () (at Assets/Scripts/pickUp.cs:13)
Hit is underlined in Visual Studio with this error. http://i.imgur.com/r881El1.png
If anyone could help, that would be great! Thanks.
Answer by mikelortega · Feb 15, 2016 at 10:26 AM
RaycastHit hit; is defined but empty, that is the null reference.
Call Physics.Raycast(transform.position, fwd, out hit, distance)
If collision is true then check hit.transform.tag (making sure it is not null).
Your answer
![](https://koobas.hobune.stream/wayback/20220612064143im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
why doesn't this Raycast compare tag work? C# 2 Answers
C# change an object tag wit raycasthit. 2 Answers
Rays and tags help? 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers