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

I'm not sure why this is throwing nil?

Asked by
pwnd64 106
9 years ago

I'm making a terminal for a clan fort and when a defender touches it I want something to happen that's different from when a raider touches it. I have a lot more code, but I cut it out to just this because this is the problem area.

Does anyone know why this throws nil?

Code -

script.Parent.Touched:connect(function(hit)
if game.Players:GetPlayerFromCharacter(hit.Parent).TeamColor == BrickColor.new("Earth green") and hit.Parent.Humanoid.Health > 0 then
print 'defender touched'
deftouched = true
0
Output.. What does it all say? Nickoakz 231 — 9y
0
Sorry, it says "Workspace.terminal.script: 12: attempt to index a nil value" pwnd64 106 — 9y

1 answer

Log in to vote
2
Answered by
Redbullusa 1580 Moderation Voter
9 years ago

Let's look at the method :GetPlayerFromCharacter(). According to the Roblox Wiki, it returns either the player itself or nil if no player is found.

So it can either be this

if pwnd64.TeamColor == BrickColor.new("Earth green")

Or this

if nil.TeamColor == BrickColor.new("Earth green")

And it's the second case that makes your script return an error. Because there's no such member as "TeamColor" in "nil." Thus, you have to first make sure that the player is not "nil."

-- Another problem is that you never closed your scopes (with "end").
script.Parent.Touched:connect(function(hit)
    local Player = game.Players:GetPlayerFromCharacter(hit.Parent)
    local Humanoid = hit.Parent:FindFirstChild("Humanoid")
    if Player and Player.TeamColor == BrickColor.new("Earth green") and Humanoid and Humanoid.Health > 0 then
        print 'defender touched'
        deftouched = true
    end
end)

Got any questions? Comments? Skepticism? Leave a comment or PM me! :)

0
Hi, thanks for the help, except now it just doesn't print or give any errors at all. It's probably because player is nil, so do you know how I can make sure that player is not nil? Thanks again. pwnd64 106 — 9y
Ad

Answer this question