NullReferenceException: Object reference not set to an instance of an object
Hi I'm kinda new to Unity and I have followed some tutorial on the Internet and I just want to be able to pick up the cutlery available in my game. This maybe the most mainstream question but I really need some help here because I don't know where or what to fix
Here's my script named InteractScript
using UnityEngine;
using System.Collections;
public class InteractScript : MonoBehaviour {
public float range;
public float interactDistance = 5f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update ()
{
if(Input.GetKeyDown(KeyCode.Mouse0))
{
Ray ray = new Ray(transform.position,transform.forward);
RaycastHit hit;
if(Physics.Raycast(ray,out hit,interactDistance))
{
if(hit.collider.CompareTag("Door"))
{
hit.collider.transform.parent.GetComponent<doorscript>().ChangeDoorState();
}
if(hit.collider.CompareTag("BigDoor"))
{
hit.collider.transform.GetComponent<BigDoor>().ChangeDoorState();
}
if(hit.collider.CompareTag("Oven"))
{
hit.collider.transform.GetComponent<Oven>().ChangeDoorState();
}
if(hit.collider.CompareTag("SlidingDoor"))
{
hit.collider.GetComponent<Animation>().Play();
}
if(hit.collider.CompareTag("Cutlery"))
{
hit.collider.GetComponent<Cutlery>().ChangeCutleryState();
}
}
}
}
}
When I try to click on my cutlery, this shows up
NullReferenceException: Object reference not set to an instance of an object InteractScript.Update () (at Assets/Script/InteractScript.cs:39)
It says on line 39 but I don't see it
Any help will be appreciated
Answer by joemane22 · Nov 14, 2015 at 07:20 AM
You need to do
hit.collider.gameObject.GetComponent<Cutlery>().ChangeCutleryState();
because you are trying to get the collider gameobject, instead of the gameobject the collider is attached to, component. Also, make sure all the objects have the right component attached.
Also, I'm not 100% sure that you have to do this just because I have always since I can remember, went to the gameobject every time I need to get a component, but I am pretty sure this is the case.
Oh thanks a lot mate, i've been so stupid not realized it haha sorry. Thanks again
Can you help me I have been geting the same error but I want to make my player move. https://answers.unity.com/questions/1792801/what-do-i-do-to-fix-this-error-i-get-it-twice-i-wa.html
Your answer
