Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Is there a way to delay the "Touched" event?

Asked by 7 years ago

Read this post from the RBXDev First:

https://devforum.roblox.com/t/repro-touched-events-delayed/38118

Touched event in parts will cause lag when they collide and get fired multiple times. Causing the server's late respondent.

Like this script inside an NPC:

01local NPC = script.Parent
02local RootPart = NPC.HumanoidRootPart
03 
04RootPart.Touched:connect(function(part)
05    if not part.Parent then return end
06    if not part.Parent:FindFirstChild('Humanoid') then return end
07    local char = part.Parent
08    local hum = char.Humanoid
09    print('It is a player!')
10end)

In-game the player touches the NPC. The server performance goes 30% down and the script printed 50x times.

But is there a way that make this still possible? If then, how?

0
In case you were wondering, both legs are going on and off the part, causing it to fire multiple times. hiimgoodpack 2009 — 7y

2 answers

Log in to vote
1
Answered by
Azarth 3141 Moderation Voter Community Moderator
7 years ago
Edited 7 years ago

Sure, use a debounce. I like using tables because then the debounce time corresponds to each player and the last time they touched that npc, rather than a variable that changes everytime the npc is touched.

01local NPC = script.Parent
02local RootPart = NPC:WaitForChild("HumanoidRootPart")
03 
04--[[
05local touchedLast = {}
06local debounce = .5
07 
08setmetatable(touchedLast, {
09    __index = function(self, key)
10        -- if the player isn't in the table, set and return their new index
11        self[key] = debounce
12        return self[key]
13    end
14})
15 
View all 43 lines...
0
Holy god man XD Audiimo 105 — 7y
Ad
Log in to vote
1
Answered by 7 years ago

Funny story. I could just use Debounce.

Answer this question