Cannot find a script compnent with raycast

Hello people :slight_smile:

I need to find a script component from the items I click on but Unity refuses to find it no matter what I do :frowning:

This is my script

using UnityEngine;
using System.Collections;

public class Pickup : MonoBehaviour {

	Camera camera;
	Collider other;
	public Inventory inventory;

	void Start(){
		camera = GetComponent<Camera>();
	}

	void  Update (){
		int x = Screen.width / 2;
		int y = Screen.height / 2;
		RaycastHit hit;
		Ray ray = camera.ScreenPointToRay(new Vector3(x, y,0));
		Debug.DrawRay (ray.origin, ray.direction * 10, Color.yellow);
		
		
		if (Input.GetMouseButtonUp(0) && Physics.Raycast(ray, out hit, 50) && hit.collider.gameObject.tag == "item") {
				print("Hit something");
				Destroy(hit.transform.GetComponent<Collider>());
				hit.transform.gameObject.active = false;
				inventory.AddItem(other.GetComponent<Item>());
		}
	}
}

And this is the error I get:

NullReferenceException: Object reference not set to an instance of an
object Pickup.Update () (at
Assets/Standard
Assets/InvScripts/Pickup.cs:26)

Does anyone know whats going on?

Thanks in advance :wink:

The NullReferenceException happens on that line :

inventory.AddItem(other.GetComponent<Item>());

This means that inventory is null. This is because you didn’t initalize it, you only declared it.

You just need to write :

public Inventory inventory = new Inventory();

Unless it is a MonoBehaviour, in which case you’d have to go with :

void Start()
{
  camera = GetComponent<Camera>();
  inventory = GetComponent<Inventory>();
}

When do you asign “other” object? I think that you never asign this variable.

Try to do:

inventory.AddItem(hit.transform.GetComponent<Item>()); 

or make first:

other = hit.transform.GetComponent<Collider>();