Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Trying to add to IntValue on player death isn't working, and returning error?

Hi so basically, I'm trying to update a value on the player leaderstats when the player dies, but my script keeps returning this error: "ServerScriptService.PlrManager:13: attempt to index nil with 'FindFirstDescendant'". I know what this is, I just don't know what's causing it, because everything looks right.

Here is my code to help:

game.Players.PlayerAdded:Connect(function(Player)
	local Container = Instance.new("Folder", Player)
	Container.Name = "leaderstats"
	
	local CurrentStage = Instance.new("IntValue", Container)
	local Tokens = Instance.new("IntValue", Container)
	local Deaths = Instance.new("IntValue", Container)
	CurrentStage.Name = "Stage"
	Tokens.Name = "Tokens"
	Deaths.Name = "Deaths"
	
	--below this is what's causing errors
	local PIW = game.Workspace:FindFirstChild(Player.Name)
	local Hum = PIW:FindFirstDescendant("Humanoid")
	Hum.OnDied:Connect(function(onDeath)
		Deaths.Value = Deaths.Value + 1
	end)
end)

1 comment

0

You don't need to do FindFirstDescendant, because the Humanoid isn't a descendant of the player. Use FindFirstChild instead.

1 answer

✓ Accepted answer

The Humanoid.OnDied Event is not a valid member, use Humanoid.Died and use Player.CharacterAdded to make the Humanoid.Died Event work.

game.Players.PlayerAdded:Connect(function(Player)
	local Container = Instance.new("Folder", Player)
	Container.Name = "leaderstats"

	local CurrentStage = Instance.new("IntValue", Container)
	local Tokens = Instance.new("IntValue", Container)
	local Deaths = Instance.new("IntValue", Container)
	CurrentStage.Name = "Stage"
	Tokens.Name = "Tokens"
	Deaths.Name = "Deaths"
	local function onCharacterAdded(char) -- Create a function when a character is spawned
		local Humanoid = char:WaitForChild("Humanoid") -- Wait for the Humanoid object to load.
		Humanoid.Died:Connect(function(...) -- Connect a function to the Humanoid.Died Event, we cannot use Humanoid.OnDied, it's not a thing.
			Deaths.Value = Deaths.Value + 1 -- Add a death to the Player List
		end)
	end
	Player.CharacterAdded:Connect(onCharacterAdded) -- Connect the onCharacterAdded function to the Player.CharacterAdded Event
	if Player.Character then -- If a character is already spawned
		onCharacterAdded(Player.Character) -- Run the function for the character.
	end
end)

2 comments

0

oh yes, i could have just created a characteradded function, thanks

0

no problem :)

This discussion is preserved as it was. New answers, comments, and votes are closed.