hi there. I am making a script where whenever a round starts, the player is inserted into a table. It works fine the first time, but in the second, instead of only inserting a specific player once, it inserts them multiple times. I can’t seem to find out why
Script:
local playersInRound = {}
players.PlayerAdded:Connect(function(player)
player.CharacterAdded:Connect(function(character)
inRound.Changed:Connect(function()
if inRound.Value == true then
print("table inround true")
table.insert(playersInRound, player) -- the next time this script runs, it just inserts the same player multiple times into the table instead of just once
end
end)
print("hello")
local humanoid = character:WaitForChild("Humanoid")
humanoid.Died:Connect(function()
local roundPlayer = table.find(playersInRound, player)
if roundPlayer then
table.remove(playersInRound, roundPlayer)
print("the player has been removed from the table")
end
end)
end)
end)
players.PlayerRemoving:Connect(function(player)
local roundPlayer = table.find(playersInRound, player)
if roundPlayer then
table.remove(playersInRound, roundPlayer)
print(playersInRound)
end
end)
I have tried that but it still does the same thing.
here is the new line of code:
players.PlayerAdded:Connect(function(player)
player.CharacterAdded:Connect(function(character)
inRound.Changed:Connect(function()
if inRound.Value == true then
print("table inround true")
table.insert(playersInRound, player)
elseif inRound.Value == false then
table.clear(playersInRound)
end
end)
it does not only remove the player when the round ends fyi. But it also removes the player when they have died or have left the game. Perhaps it has something to do with that?
Every time the player respawns you’re connecting a new inRound.Changed event and so it fires multiple times after the first line since there are multiple events connected. You should disconnect this when they die.
local inRoundCon = nil
player.CharacterAdded:Connect(function(character)
inRoundCon = inRound.Changed:Connect(function()
-- code
end
humanoid.Died:Connect(function()
if inRoundCon then
inRoundCon:Disconnect()
end
-- code
end)
end)
It managed to work for one player but for the rest it just adds them to the table twice. I can show the output.
Here is the new script:
local inRoundCon = nil
players.PlayerAdded:Connect(function(player)
player.CharacterAdded:Connect(function(character)
inRoundCon = inRound.Changed:Connect(function()
if inRound.Value == true then
print("table inround true")
table.insert(playersInRound, player)
elseif inRound.Value == false then
table.clear(playersInRound)
end
end)
local humanoid = character:WaitForChild("Humanoid")
humanoid.Died:Connect(function()
if inRoundCon then
inRoundCon:Disconnect()
end
local roundPlayer = table.find(playersInRound, player)
if roundPlayer then
table.remove(playersInRound, roundPlayer)
print("the player has been removed from the table")
end
end)
end)
end)