What is the best way to determine when a part is longer being hit by a raycast?

I’m creating a game that uses a lot of raycasting. Some of this raycasting is used to activate things, such as raycasting down from a box looking for a button to activate. Basically, I need to activate something when a raycast hits it, but deactive it when the raycast is no longer hitting it.

I’ve created hacky solutions that I’m not super proud of. For the box and button relationship, I created a dictionary with each box being paired with a number. Each time the box’s raycast hits the button, that number increments. I detect the box leaving the button when that number is no longer incrementing.

I’m now making a new system that is similar, and the dictionary method won’t work for it. So what would be the most efficient way to deactive something when a raycast is no longer hitting it?

Raycasting only takes place when you call findpartonray or some other variant of that api so I dont get what you mean, why not just cast the ray and check if the part the ray is touching the desired part.

The problem isn’t detecting the ray hitting the part, it’s detecting when the ray is no longer hitting that part. There are multiple boxes and there are multiple buttons, with all of their interactions being handled inside of a module. I can’t simply do something like

if partOnRay then

Modify your module to support an enabled and disabled function

I don’t see what you mean?

I have functions to both activate and deactivate the objects, but when to call the deactivate function is the question.

You would have to raycast on every heartbeat and check if its touching the desired part and if not then you disable it. To limit the frequency you can add an interval check to wait until a certain amount of time has elapsed since the last check

Except I can’t do that. Say I have two boxes and one button. I loop through the boxes, and the first box’s raycast detects a button, so I activate it. If the second box’s raycast doesn’t detect the button, I would instantly be undoing that action.

The just break from the loop once its detected? and you would save the box that detected it and check on the next iteration if either that box does not detect it anymore or another bother detects it.