How to interact with closed doors
Hello community,
I am having trouble with getting doors to open when I use a raycast to open them. I keep geting a error saying NullReferenceException: Object reference not set to an instance of an object. Here is my code:
void Update () { //checks for left mouse click if(Input.GetKeyDown(KeyCode.Mouse0)) { Ray ray = new Ray(transform.position, transform.forward); RaycastHit hit;
//shoot a ray
if (Physics.Raycast(ray, out hit, interactDistance, interactiveLayer))
{
//Checks if we are not interacting
if(isIntereacting == false)
{
if (interactIcon != null)
{
interactIcon.enabled = true;
}
//If its a door
if (hit.collider.CompareTag("Door"))
{
hit.collider.transform.parent.GetComponent<DoorCTRL>().RotateDoor();
}
}
}
}
Much thanks everyone!
what line number does the error appear on , double click on the error in unity and it should take you to the line
I am going to help with some error possibilities since we do not know the exact line number:
If the raycast fails to hit anything, the 'hit' object will be null. Always check if it hits anything before proceeding.
If the collider is on a root gameobject, the transform.parent reference will also return null. Check if the returned hit.collider.transform has a parent.
If there is a parent object, which does not have a 'DoorCTRL' component on it, the GetComponent function will also return null. Check if the parent object has this component attached to it.