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

Why is there an Error 'attempt to index nil' onTouched?

Asked by 3 years ago

This script is meant to check when a player touches the brick, then checks if they are on a certain team, and should kill them. But when testing in game, I get an error on line 7; attempt to index nil with 'TeamColor'

local Players = game:GetService("Players")

local part = script.Parent

local function onTouched(part)
    local player = Players:GetPlayerFromCharacter(part.Parent)
    if player.TeamColor == "Institutional white" then
        player.Character.Humanoid.Health = 0
    end
end

part.Touched:Connect(onTouched)

1 answer

Log in to vote
0
Answered by
Xapelize 2658 Moderation Voter Community Moderator
3 years ago

Because the "hit" that was touching the part was not a player, hence describing Players:GetPlayerFromCharacter(part.Parent) will return nil. Do:

if player and player.TeamColor == "Institutional white" then
Ad

Answer this question