Help with not disappearing image in unity!

Hello, I’m trying to make a script that is enabling a image in canvas (doorTrigger object) when im looking at doors using raycast. It works, except one problem. When I look away from door it wont disappear. I don’t know how to fix it.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class InteractionSystem : MonoBehaviour
{
    public GameObject doorTrigger;
    public Transform rayTarget;

    Transform lastHittedObject;

    GameObject controlsManager;
    Controls controls;

    private void Start()
    {
        controlsManager = GameObject.FindGameObjectWithTag("Controls");
        controls = controlsManager.GetComponent<Controls>();
        doorTrigger.SetActive(false);
    }

    private void Update()
    {
        Ray ray = new Ray(rayTarget.transform.position, rayTarget.transform.forward * 1);
        RaycastHit hit;

        Debug.DrawRay(rayTarget.transform.position, rayTarget.transform.forward * 1, Color.blue);

        if (Physics.Raycast(ray, out hit, 1))
        {
            if(hit.transform.tag == "Door")
            {
                //Debug.Log("door");
                doorTrigger.SetActive(true);
                Animator anim = hit.transform.GetComponentInChildren<Animator>();
                if (Input.GetKeyDown(controls.interactionButton))
                {
                    anim.SetTrigger("OpenClose");
                    doorTrigger.SetActive(false);
                }
            }
            else if(hit.transform.tag != "Door")
            {
                doorTrigger.SetActive(false);
            }
        }
    }
}

If the door opens and the Physics.Raycast returns false it doesn’t do anything. You need an else to handle when no raycast hit happens.

2 Likes

what @Chris-Trueman said.

also this -

if(hit.transform.tag == "Door")
            {
                //Debug.Log("door");
                doorTrigger.SetActive(true);
                Animator anim = hit.transform.GetComponentInChildren<Animator>();
                if (Input.GetKeyDown(controls.interactionButton))
                {
                    anim.SetTrigger("OpenClose");
                    doorTrigger.SetActive(false);
                }
            }
            else if(hit.transform.tag != "Door")
            {
                doorTrigger.SetActive(false);
            }

in the else here you don’t have to re-check that the tag isn’t “Door”, if you’ve ended up here it’s because tag == Door is already false, you can just say “else” without the “if (condition)”.