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

ServerScriptService.Script:4: attempt to index nil with 'UserId' Can Somebody Help Me?

Asked by 3 years ago

So I have an error in my code. I have been trying to give all players a hat when they spawn however I get an error for some reason. I would really appreciate it if you could help me.

I get this error: ServerScriptService.Script:4: attempt to index nil with 'UserId' Script 'ServerScriptService.Script', Line 4

Anyways this is my code:

    local players = game:GetService("Players")
    local serverStorage = game:GetService("ServerStorage")

    local users = players.LocalPlayer.UserId

    local isAllowed = function(player, tab)
    for i, v in pairs(tab) do
        if player.UserId == v then return true end
    end
    return false
    end

    players.PlayerAdded:Connect(function(player)

        player.CharacterAdded:Connect(function(character)
        local hat = serverStorage:WaitForChild("Combat Helmet") 
        if isAllowed(player, users) then
            local clone = hat:Clone()
            clone.Parent = character
        end
    end)

end)

1 answer

Log in to vote
0
Answered by 3 years ago

Simple.

The server can not use LocalPlayer as it is never defined only local scripts can use it

Also if your trying to get all the players you need a table not a userid.

Your code should look something like this:

    local players = game:service("Players") -- or :GetService('Players')
    local serverStorage = game:service("ServerStorage") -- or :GetService('ServerStorage')

    local users = players:players() -- or :GetPlayers()

    local isAllowed = function(player, tab)
    for i, v in pairs(tab) do
        if player.UserId == v then return true end
    end
    return false
    end

    players.PlayerAdded:Connect(function(player)

        player.CharacterAdded:Connect(function(character)
        local hat = serverStorage:WaitForChild("Combat Helmet") 
        if isAllowed(player, users) then
            local clone = hat:Clone()
            clone.Parent = character
        end
    end)

end)
0
So i make a local script? FireTap1 12 — 3y
0
No you can use a normal script if you use the code i gave you also yours wasn't giving the for loop a table so it would not have worked anyways Harry_TheKing1 325 — 3y
Ad

Answer this question