- Home /
Question by
Brae10 · Jul 25, 2015 at 12:05 AM ·
errornullreferenceexceptionpickupitem
[answered] How to fix an error on my Item Collection Script?
I'm making a script to check if a ray has hit a gameobject with a certain tag, but i have encounter a problem with this error:
NullReferenceException: Object reference not set to an instance of an object ItemCollection.Update () (at Assets/Scripts/ItemCollection.cs:24)
The line where the error occurs is: if (hit.collider.gameObject.tag == "Collectable") {
using UnityEngine;
using System.Collections;
public class ItemCollection : MonoBehaviour {
public int rayLength;
public int items = 0;
bool gui = false;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
RaycastHit hit = new RaycastHit();
Vector3 fwd = transform.TransformDirection(Vector3.forward);
Debug.DrawRay (transform.position, fwd);
if (Physics.Raycast (transform.position, fwd, rayLength)) {
if (hit.collider.gameObject.tag == "Collectable") {
gui = true;
if (Input.GetButtonDown ("Interact")) {
items ++;
Destroy(hit.collider.gameObject);
gui = !gui;
}
}
else {
gui = false;
}
}
}
void OnGui() {
if (gui == true) {
GUI.Box(new Rect(Screen.width / 2 - 150, Screen.height / 2 - 150, 100, 20), "Press 'E' to Collect");
}
}
}
Comment
Best Answer
Answer by DoTA_KAMIKADzE · Jul 25, 2015 at 12:10 AM
You don't retrieve your raycast, e.g. change your line #22 (24 in your real script?) to this:
if (Physics.Raycast(transform.position, fwd, out hit, rayLength))
also you don't need to do that in your line #17, that will be enough:
RaycastHit hit;
and you've missed "using UnityEngine;" in provided code.
Your answer
![](https://koobas.hobune.stream/wayback/20220611232929im_/https://answers.unity.com/themes/thub/images/avi.jpg)