So I am trying to make a danger block, which touches lots of players at once. I added a debounce, so it doesn’t kill players at one touch. But, it keeps setting the debounce for every player, so some players take no damage. Is there a way to make debounce for every player?
I’d create a table, and when players join I would insert them into that table. For example:
local debounces = {}
game.Players.PlayerAdded:Connect(function(player)
debounces[player.Name] = false
end)
You’d also have to do the same thing for when the player is leaving except you would make the table nil
instead of false
.
If you already have the player name for when you touch the player, then you’d call the table like in the function above, except you’d set the debounce to true
. Basically you can use that as a normal debounce. If this needs more clarification don’t be afraid to ask.
Thank you I was also looking for it
This is a dictionary rather than a table. Also you don’t need to add the player in on join, just on their first touch.
local dictionary = {}
brick.Touched:Connect(function(hit)
local player = game.Players:GetPlayerFromCharacter(hit.Parent)
if player and not dictionary[player.Name] then --nil or false
dictionary[player.Name] = true
damagePlayer()
wait(5) --change to whatever debounce
dictionary[player.Name] = nil
end
end)
This is actually a better solution, and now I can say I learned something today.
Why not make it nil? It saves memory usage, but I digress.
As @FilteredDev mentioned,
I’d just like to add why this will cause leakage over time. When players leave, they will not be garbage collected from the table. Eventaully, there will be thousands of indexs, so if enough players play your game, it will eventually cause lag and bring the server to a halt.
A dictionary is a type of table. Calling it a table is still correct. This is an array: {1,2}
, this is a dictionary {a = 1, b = 2}
, and this is a mixed table: {1, a = 1}
. All of them fall under the general category of table.
Good ole “A square is a rectangle but a rectangle is not necessarily a square”.
@SteveCShel
You can make it a weak table, so that it doesn’t hold the player object hostage.
table._mode = ‘k’
(I personally would just use the player reference. I’m lazy and a lot of .Name’s is too much work for my poor wittle fingers.)
That and when the player leaves their player will be GC’d and the entry will be removed so that you keep only active players in the table.
local debounce = {}
--example use case, given target is the part you want to track touch events on
target.Touched:Connect(function(part)
--code to get player
if not debounce[player.UserId] then
debounce[player.UserId] = true
--do whatever you want to do here
delay(0.1, function() debounce[player.UserId] = false end)
end
end)
I don’t know how efficient this is, if I messed up please let me know. But this is how I would handle it