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

I'm not sure why this is throwing nil?

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

2 comments

0

Output.. What does it all say?

0

Sorry, it says "Workspace.terminal.script: 12: attempt to index a nil value"

1 answer

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! :)

1 comment

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.

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