I'm working on a leaderboard and I have a function that fires when a player dies, however, it doesn't fire on the first death, it only happens on the second death of the player in the server. Here is my code in a ServerScript in ServerScriptService:
game.Players.PlayerAdded:connect(function(player) local PauseButtonEvent = Instance.new("RemoteEvent") PauseButtonEvent.Parent = game.ReplicatedStorage PauseButtonEvent.Name = "PauseButtonEvent" player.CharacterAdded:connect(function(character) humanoid = character.Humanoid print(player.Name .. " died") transport(player) PauseButtonEvent:FireClient(player) humanoid.Died:connect(function() deaths.Value = deaths.Value + 1 for i, child in pairs(humanoid:GetChildren()) do if child:IsA("ObjectValue") and child.Value and child.Value:IsA("Player") then local killer = child.Value if killer:FindFirstChild("leaderstats") and killer:FindFirstChild("Kills") then local killerKills = killer.leaderstats.Kills killerKills.Value = killerKills.Value +1 end return end end end) end) end)
Also, if you see anything else wrong with my code beside what is causing the problem I explained, please tell me. Also, the game has filtering enabled.
Thank you in advance for any help.
I believe this is to do with the character spawning before the function has fully completed. I've met this a few times when coding my own scripts, so I prefer to do something along these lines:
loaded = function(character) humanoid = character.Humanoid transport(player) PauseButtonEvent:FireClient(player) humanoid.Died:connect(function() deaths.Value = deaths.Value + 1 for i, child in pairs(humanoid:GetChildren()) do if child:IsA("ObjectValue") and child.Value and child.Value:IsA("Player") then local killer = child.Value if killer:FindFirstChild("leaderstats") and killer:FindFirstChild("Kills") then local killerKills = killer.leaderstats.Kills killerKills.Value = killerKills.Value +1 end return end end end) end game.Players.PlayerAdded:connect(function(player) local PauseButtonEvent = Instance.new("RemoteEvent") --Not sure why you want to make a new one every time the player joins... PauseButtonEvent.Parent = game.ReplicatedStorage PauseButtonEvent.Name = "PauseButtonEvent" repeat wait() until player.Character loaded(player.Character) player.CharacterAdded:connect(function(character) loaded(character) end) end)
So it waits until the character has first loaded before running the code.