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

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

Asked by 6 years ago
Edited 6 years ago

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

Log in to vote
0
Answered by
obcdino 113
6 years ago
Edited 6 years ago

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)
0
OHHHHHHHH Cool thanks. JayQwery 0 — 6y
Ad

Answer this question