Most efficient way to detect when a person touches and stops touching an object?

Hello, recently I’ve been trying to create an efficient system that detects when a player touches an object then stops touching that object. The reason I have created this thread is because while I have found a reasonable solution, it uses a while loop, which concerns me. My main question is, are you guys familiar with a better way (or really efficient way) to detect when a person starts and stops touching an object? My two attempts are down below.

My first attempt was to use the .Touched and .TouchEnded events (along with the GetTouchingParts method) to detect when a player initially touched the object; the player’s character was then added to a table. When the object stopped touching something, GetTouchingParts was used to see if the player wasn’t touching the object any longer. The code is here (how does a person insert code into the post?):

Here is a GIF of this method not working how I intended (see output):
https://gyazo.com/705c11882ad7fae107e3fd074a699e97

The second method I used was based on Region3’s. By using a while true do loop, in each iteration I called a function that added players that were in the Region3 to a table, and then removed players that were not in the Region3 from the table. The code is here:

Here is a GIF of this method working (see output):
https://gyazo.com/ee6a1113be3d5d5ce77821028b62edc5

Let me know what you think! Thanks.

12 Likes

I have used a Touched event to trigger a loop that detects whether or not the player is in a region. If the player isn’t in the region, the loop will break, avoiding unnecessary looping.

2 Likes

Alternate Options

  • Magnitude check for the player if close enough, don’t loop this too often.
  • Region3 as mentioned above and break it after leaving.

All of this needs to be connected to a Touched signal. Add debounce to avoid unnecessary amount of loops and utilize the while loop correctly would do.

11 Likes

Using magnitude will be much easier but will not be as efficient as Region3