Hello!
I want to track the number of times a player dies in a match.
When there’s only one player in the match, my code works as expected, however once you add other players into the mix my code starts generating strange results. Death counts change unpredictably, and the totals at the end are wildly off-base.
I suspect the issue has something to do with multiple simultaneous calls to the death count update code, or variable crosstalk somewhere, but I’m not familiar enough with having all these asynchronous events and function calls flying everywhere to know where to start debugging.
I’ve tried adding local LocalPlayer = Character.Parent just after Player.CharacterAdded:Connect(function(Character), but that causes crashes all over the place.
Here’s my current death tally update code:
local function PreparePlayer(Player)
-- Zero out the player's death tally for the new match
UpdatePlayerDeathTally(Player, function(_) return 0 end)
Player.CharacterAdded:Connect(function(Character)
ForceFieldHandler.Create(Player, GameSettings.FORCE_FIELD_DURATION)
task.spawn(function()
local Humanoid = Character:WaitForChild("Humanoid")
Humanoid.Died:Connect(function()
UpdatePlayerDeathTally(Player, function(CurrentDeaths)
CurrentDeaths = CurrentDeaths or 1
return CurrentDeaths + 1
end)
Humanoid.JumpPower = GameSettings.DEFAULT_JUMP_POWER
Humanoid.WalkSpeed = GameSettings.DEFAULT_WALK_SPEED
PlayerData.UpdateValue(Player, JUMP_BONUS_KEY, function() return 0 end)
PlayerData.UpdateValue(Player, SPEED_BONUS_KEY, function() return 0 end)
PlayerData.UpdateValue(Player, GREED_LEVEL_KEY, function() return 0 end)
end)
end)
end)
end
And
local function UpdatePlayerDeathTally(Player, UpdateFunction)
local NewDeathTally = PlayerData.UpdateValue(Player, DEATH_TALLY_KEY, UpdateFunction)
LeaderboardHandler.SetStat(Player, DEATH_TALLY_KEY, NewDeathTally)
-- Updates death tally in player GUI
UpdateDeathsRemote:FireClient(Player, NewDeathTally)
end