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

Attempt to index field localplayer a nil value?

local isTrue = game.Players.LocalPlayer.Backpack:FindFirstChild("ClassicSword") if isTrue then print("It Works") end

when I use this code it says ServerScriptService.Script:1: attempt to index field 'LocalPlayer' (a nil value)

anyone know how to fix this

3 answers

✓ Accepted answer

You are only able to access the LocalPlayer through a LocalScript, otherwise the server script doesn't know what player you are referring to when you use LocalPlayer. If you want to check every player instead with a server script, you can use PlayerAdded:

game.Players.PlayerAdded:Connect(function(Plr)
	local ClassicSword = Plr.Backpack:WaitForChild("ClassicSword",5)
	if ClassicSword then
		print("it works")
	end
end)

If you wanted to print when a classic sword was added to the backpack instead, you could do something like this with ChildAdded:

game.Players.PlayerAdded:Connect(function(Plr)
	Plr.Backpack.ChildAdded:Connect(function(Child)
		if Child.Name == "ClassicSword" then
			print("sword was added")
		end
	end)
end)

The PlayerAdded and ChildAdded events fire every time a player joins/child is added.

Hope this helps!

1 comment

0

Thanks

The problem might be that you're not using a local script or the local script isn't in a place where it can run on the player (playergui, backpack; starterpack)

LocalPlayer is client-side only. Try using a LocalScript instead of a server Script.

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