How to detect that a collider has moved out of the raycast instantly?

What I want to do is very simple: I constantly cast a ray in front of my character so when it detect something that can be interacted with (like a door), a little hint is rendered thanks to a canvas in the UI of the player.


My code works for stationary objects. But, if the raycast hits a door, and this door is opened, the hint doesn’t disappear and still consider that the door – which is now rotated and, in fact, not anymore at the range of the ray – that the door is still in range.


It seems that the raycast doesn’t update when something is moved. How can I make a hint appear when the player is in range to an interractable object?


Here’s my actual code: (door = anything interractable)

using UnityEngine;

public class InteractScript : MonoBehaviour {
    public float interactDistance = 3f;
    public Canvas rend;

    void Start()
    {
        var Hint2= GameObject.Find("Hint");
        rend = Hint2.GetComponent<Canvas>();
        rend.enabled = false;
    }

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


        if (Physics.Raycast(ray, out hit, interactDistance))
        {
            if (hit.collider.CompareTag("Door"))
            {
                rend.enabled = true;
                if (Input.GetKeyDown(KeyCode.Mouse0))
                    {
                    hit.collider.transform.parent.GetComponent<DoorScript>().ChangeDoorState();
                    }
            }
            else
            {
                rend.enabled = false;
            }
        }
    }
}

So here’s what you’re doing:

If there is a hit within interact distance
{
If it is a door -> render hint
Otherwise -> stop rendering hint
}

Your statement to stop rendering the hint is only ever set if the object is hit, making it within the interact distance, it needs to be outside the interact distance… it’s an easily overlooked logic bug.

Perhaps add something to the door that:

while hint active -> check distance to the player
when distance to player > interact distance 
disable hint.