Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Why is v.Character a nil value?

Asked by
Seyfert 90
8 years ago
Edited 8 years ago

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)
0
Well, the player just left, since it's in a PlayerRemoving event. So why should a player that just left have a character? GoldenPhysics 474 — 8y
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? Seyfert 90 — 8y
0
Put line 7 inside the if statement right after it then. You have to check for the character for that, too. GoldenPhysics 474 — 8y

2 answers

Log in to vote
0
Answered by 8 years ago
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.

Ad
Log in to vote
-1
Answered by 8 years ago

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

Answer this question