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

Why is v.Character a nil value?

This script is located in ServerScriptService and when it runs in Play mode it keeps telling me that Character is a nil value

game.Players.PlayerRemoving:connect(function(player)

		for i, v in pairs(game.Players:GetChildren()) do
			if v.TeamColor == BrickColor.new('Bright red') then
				v.TeamColor = BrickColor.new("Bright yellow")
			end
			v.Character.Humanoid:UnequipTools()
			if v.Character.Humanoid ~= nil then
				v.Character:BreakJoints()
			end
		end

end		
end)

3 comments

0

Well, the player just left, since it's in a PlayerRemoving event. So why should a player that just left have a character?

0

@GoldenPhysics, yes, what I was hoping the for i, v in pairs would do is loop through all remaining players and kill them. Though if that doesn't work, would the best idea be to have a LocalScript call a remote event and do the killing in another script?

0

Put line 7 inside the if statement right after it then. You have to check for the character for that, too.

2 answers

game.Players.PlayerRemoving:connect(function(player)
    for i, v in pairs(game.Players:GetPlayers()) do
        if v.TeamColor == BrickColor.new('Bright red') then
            v.TeamColor = BrickColor.new('Bright yellow')
        end
        if v.Character and v.Character.Humanoid then
		v.Character.Humanoid:UnequipTools()
        	v.Character:BreakJoints()
        end
    end
end

Your original problem was that you were looping through all players and referring to the players character when not all players had a character. To fix this, you must check that each player has a character, which you did when you called :BreakJoints(), but not when you called :UnequipTools().

The problem with ElectroTM's answer is the return. Once you return from a function, the script exits the function, so as soon as it detects that a player doesn't have a character, it will stopped checking the rest of the players.

Since you're running into the character being nil, just return if the player has no character. (same for the humanoid)

game.Players.PlayerRemoving:connect(function(player)
	for i, v in pairs(game.Players:GetPlayers()) do
		if v.TeamColor == BrickColor.new('Bright red') then
			v.TeamColor = BrickColor.new('Bright yellow')
		end
		if not v.Character or not v.Character.Humanoid then
			return
		end
		v.Character.Humanoid:UnequipTools()
		v.Character:BreakJoints()
	end
end

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