I’m trying to detect when a player has died and remove them from a table. However, the approach I’m using fires multiple times (Mostly 4 times). Is there a way I can get this to only fire once?
A temporary approach that works is:
Creating an “InRound” variable for the player in Script 1
Detecting when the player has died in a Script 2 and deleting “InRound”
Checking to see if “InRound” is present in Script 1. If not, presume they’re dead
Instead, I would like to do everything in one main script if possible.
Here’s my code: Note - Although I’m using for loops, I’m quite certain that this is not the underlying problem.
“creator” is the killfeed from the original Roblox Sword, it’s an ObjectValue of a player
for x = RoundTime, 0, -1 do
Status.Value = "Round - "..TFM:Convert(x, "Default", true) -- Time formatting module (110 --> 01:50)
-- Checks if they're still playing
for i, Player in pairs(AlivePlayers) do
local Humanoid = Player.Character:WaitForChild("Humanoid")
Humanoid.Died:Connect(function()
if Humanoid:FindFirstChild("creator") then
-- They were killed by another player
local ResponsiblePlayer = Humanoid.creator.Value
ResponsiblePlayer.leaderstats.Tokens.Value += 5
print(Player.Name.." was killed by "..ResponsiblePlayer.Name)
else
-- They just died
print(Player.Name.." is dead")
end
table.remove(AlivePlayers, i)
end)
end
It fires multiple times because you are connecting the event every iteration of the loop. You should either move the Humanoid.Died:Connect() code above the loop, or disconnect all the events before reconnecting.
This Should clear stuff out a bit (I haven’t run these but they should be fine)
--> First Approach With .Health
for x = RoundTime, 0, -1 do
Status.Value = "Round - "..TFM:Convert(x, "Default", true) -- Time formatting module (110 --> 01:50)
-- Checks if they're still playing
for i, Player in pairs(AlivePlayers) do
local Humanoid = Player.Character:WaitForChild("Humanoid")
if Humanoid.Health <= 0 then
table.remove(AlivePlayers,i)
if Humanoid:FindFirstChild("creator") then
-- They were killed by another player
local ResponsiblePlayer = Humanoid.creator.Value
ResponsiblePlayer.leaderstats.Tokens.Value += 5
print(Player.Name.." was killed by "..ResponsiblePlayer.Name)
else
-- They just died
print(Player.Name.." is dead")
end
end
end
end
--> Second Approach with a Global Table of Players Alive
local AlivePlayers = {} --> Store Somehow Maybe by Looping through them all Once
for i, Player in pairs(AlivePlayers) do
local Humanoid = Player.Character:WaitForChild("Humanoid")
Humanoid.Died:Connect(function()
if Humanoid:FindFirstChild("creator") then
-- They were killed by another player
local ResponsiblePlayer = Humanoid.creator.Value
ResponsiblePlayer.leaderstats.Tokens.Value += 5
print(Player.Name.." was killed by "..ResponsiblePlayer.Name)
else
-- They just died
print(Player.Name.." is dead")
end
table.remove(AlivePlayers, i)
end)
end