Not sure what this error is telling/asking me to do?
I watched a video on an interaction script (because I suck at scripting), and I did all according to plan. However, I get this error message "NullReferenceException: Object reference not set to an instance of an object Interact.Update() (at Assets/Interact.cs:50)" and i have no idea what it is telling me to do in order to fix it.
My code: using UnityEngine; using System.Collections; using UnityEngine.UI;
public class Interact : MonoBehaviour
{
public string interactButton;
public float InteractDistance = 3f;
public LayerMask interactLayer; //filter
public Image interactIcon; //Picture to show if you can interact or not
public bool isInteracting;
// Use this for initialization
void Start ()
{
//set interact icon to be invisible
if(interactIcon != null)
{
interactIcon.enabled = false;
}
}
// Update is called once per frame
void Update ()
{
Ray ray = new Ray(transform.position, transform.forward);
RaycastHit hit;
//Shoots a ray
if(Physics.Raycast(ray, out hit, InteractDistance, interactLayer))
{
//Checks if we are not interacting
if (isInteracting == false)
{
if(interactIcon != null)
{
interactIcon.enabled = true;
}
//If we press the interaction button
if (Input.GetButtonDown("Interact"))
{
//If it is a Door
if (hit.collider.CompareTag("Door"))
{
//Open or Close it
hit.collider.GetComponent<Door>().ChangeDoorState();
}
}
}
}
}
}
Line 50 = hit.collider.GetComponent().ChangeDoorState();
I thought it was telling me to name the gameobject "Door" but i guess thats not the issue :( Thanks!
Edit: The error occurs when I walk up to the door and press my Interact Button
It basically means there is no door available to execute the action on.
(hit.collider.GetComponent() as Door).ChangeDoorState();
Try overloading the type. Also do a null check on the Door Script like this:
if ( !hit.collider.GetComponent() ){ return; }
Answer by jdean300 · Jul 09, 2016 at 06:18 AM
The object that the Ray cast hit does not have a door component. Try using Debug.Log to print out the value of hit.collider and hit.collider.gameObject to make sure you are hitting the object you expect, and make sure there is a Door component in that object.
Your answer
Follow this Question
Related Questions
I need help I can't find the error in my code! 1 Answer
NullReferenceException: Object reference not set to an instance of an object 3 Answers
Null Reference in UnityStandardAssets.Utility.WaypointProgressTracker.Update 0 Answers
Can someone explain to me how FileUtil.CopyFileOrDirectory works ? 0 Answers
how to connect external display to second camera in unity? 0 Answers