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

Attempt to index field localplayer a nil value?

Asked by 6 years ago

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

Log in to vote
2
Answered by
mattscy 3725 Moderation Voter Community Moderator
6 years ago

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!

0
Thanks Madkiller672 4 — 6y
Ad
Log in to vote
0
Answered by
T1mes 230 Moderation Voter
6 years ago

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)

Log in to vote
0
Answered by 6 years ago

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

Answer this question