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

Why is it being indexed as a nil Value???

I am confused, I'm consistently getting an error but the script works correctly.

Just an example of the type of code I'm talking about. Not the entire code just the pertinent lines.

local rt = game.Workspace.redteam

function teamchange(p1,color)
	game.Players:FindFirstChild(p1).TeamColor = BrickColor.new(color) --Line 31
end

rt.Touched:connect(function(hit)
	print(hit.Parent)
	teamchange(hit.Parent.Name,"Really red")
end)

The console always says this:

ServerScriptService.Main Script:31: attempt to index a nil value

1 answer

You aren't checking if hit has a humanoid.

This is easily fixed with:

local rt = game.Workspace.redteam

function teamchange(p1,color)
    game.Players:FindFirstChild(p1).TeamColor = BrickColor.new(color) --Line 31
end

rt.Touched:connect(function(hit)
    print(hit.Parent)
	if hit.Parent:FindFirstChild("Humanoid") then
	teamchange(hit.Parent.Name,"Really red")
	end
end)

A better fix would to check if the humanoid correlates to a player, using GetPlayerFromCharacter, which checks if a character is linked to a player.

local rt = game.Workspace.redteam

function teamchange(p1,color)
    game.Players:FindFirstChild(p1).TeamColor = BrickColor.new(color) --Line 31
end

rt.Touched:connect(function(hit)
    print(hit.Parent)
	if hit.Parent:FindFirstChild("Humanoid") and game.Players:GetPlayerFromCharacter(hit.Parent) then
	teamchange(hit.Parent.Name,"Really red")
	end
end)

1 comment

0

OHHHHHHHH Cool thanks.

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