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

Attempt to index field localplayer (a nil value)?

I have this script that is not working for some reason. when i play it says Attempt to index field localplayer (a nil value) line 8 It looks right to me. is there anything wrong with it?

local enabled = true
script.Parent.Touched:connect(function(hit)
if enabled == true then
	enabled =false	
	local name = hit.Parent.Name
	local hunger = game.Workspace.hungervalues:FindFirstChild(name)
	local player = game.Players.LocalPlayer
	local humanoid = player.Character.Humanoid
	local anim = Instance.new("Animation")
	anim.AnimationId = "http://www.roblox.com/asset/?id=633050771"
	local playAnim = humanoid:LoadAnimation(anim)
	humanoid.WalkSpeed = 0
	playAnim:Play()
	wait(1.5)		
	playAnim:Stop()
	hunger.Value = hunger.Value + 5
	script.Parent:Destroy()	
	humanoid.WalkSpeed = 16
	enabled = true
end
end)
while true do
	wait(60)
	script.Parent:Destroy()
end
	

2 answers

The reason why this happens is because LocalPlayer is only available in localScripts, as those run on the client. Now don't quickly think, "i'll just change this to a localscript, problem solved!" because that will not fix your problem.

You'll have to use the GetPlayerFromCharacter method from the Players Service.

local player = game.Players:GetPlayerFromCharacter(hit.Parent)

However, as your code runs now, it'll error on anything that isn't a player.

You'll have to add this line right after your function, to see if the thing that touched it is a valid characterModel:

if hit.Parent:FindFirstChild("Humanoid") then

Hopefully this helps you enough with your problem.

If you have any questions, post a comment down below.

I have a question where is this script located and what kind script is executing it? local script? Script?

You could change localplayer to

game:GetService("Players"):FindFirstChild(name)

1 comment

0

That should be a comment ;p

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