A glitch sometimes happens when the player dies

I have a minigame system that detects when a player dies. The issue here is that it sometimes breaks. I have yet to find a solution to this.Here is the code

for i, player in pairs(game.Players:GetPlayers()) do
			if player.CharacterAppearanceLoaded and player.Character then
				table.insert(playersInRound, player)
				table.insert(playerInRoundNames, player.Name)
			end
			player.Character:WaitForChild("Humanoid").Died:Connect(function()
				local ind = table.find(playersInRound, player)
				if ind then	
					table.remove(playersInRound, table.find(playersInRound, player))
					table.remove(playerInRoundNames, table.find(playerInRoundNames, player.Name))
				end
				for _, player in pairs(game.Players:GetPlayers()) do
					player.PlayerGui.Gamemode.PlayersLeft.PlayersLeftText.Text = #playersInRound
				end
			end)
		end

the error is "attempt to index nil, with ‘WaitForChild’

that is because the loop is still running and if the player dies while the loop is looping another player and then loops that player then it will throw an error

How would I fix this. I don’t really know of a way to fix this.

Just add a value of IsAlive in the player

and the added players script
its a really simple way to implement but I think you could do something better

game.Players.PlayerAdded:Connect(function(Player)
    Player.CharacterAdded:Connect(function(Character)
         -- creates a value for IsAlive
         local IsAlive = Instance.new("BoolValue")
         IsAlive.Name = "IsAlive"
         IsAlive.Parent = Player

         Character.Humanoid.Died:Connect(function()
              IsAlive:Destroy() -- other words false
         end)
    end)
end)

What would make the difference with having the isAlive value though?

is that you can just check in the player if its in there or not

Sorry im kinda beginner scripter, i’ve tried this ingame, but it doesn’t seem to be fixing my problem.

you could fire events from modules

really don’t recommend this since you are a Beginner Scripter

Could you try

local Character = player:WaitForChild("Character", 5)
Character.Humanoid.Died:Connect(function()
    --Insert stuff here
end)

Or you can go ahead and add print statements to figure out where the error could possibly lie?

What does the 5 mean when you call for character?

The number just means how long it will attempt to find that certain variable before it times out (I believe)

That just completely breaks the script. i’m out of ideas.

Might wanna consider adding print statements to define what’s what then :thinking:

1 Like