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

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

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

✓ Accepted answer

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

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