- Home /
The question is answered, right answer was accepted
Cannot find a script compnent with raycast
Hello people :)
I need to find a script component from the items I click on but Unity refuses to find it no matter what I do :(
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 ;)
Is 'inventory' set in the inspector? That's what line 26 is looking for.
Answer by DominikP · Jan 11, 2016 at 03:29 PM
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>();
Yes awesome that's it :D Totally forgot about the "other" thing^^ Thank you!! :D
Answer by corn · Jan 10, 2016 at 04:39 PM
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>();
}
Hi thanks :)
I tried it, but it still didn't initalize it. Then I just initialized it in the inspector which worked :D
But I still get this error:
NullReferenceException: Object reference not set to an instance of an object Pickup.Update () (at Assets/Standard Assets/InvScripts/Pickup.cs:26)
So I still think it's because of the "Item" component