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

Why can I not get rid of the "attempt to index nil with 'UserId'" error in my script?

Asked by 3 years ago

So I've been trying for quite a while now to make a Kills leaderstats that saves with DataStores on exit but I keep getting error after error. Finally, when I thought I had solved it, I got another error and I can't fix this one. I just want one of you to either revise my script so I don't get any errors or give me a better Kills script that also saves on exit.

Here is my script below:

local DataStoreService = game:GetService("DataStoreService") local DataStore = DataStoreService:GetDataStore("KillStats")

game.Players.PlayerAdded:Connect(function(plr)

local stats = Instance.new("Folder")
stats.Name = "leaderstats"
stats.Parent = plr

local kills = Instance.new("IntValue")
kills.Name = "Kills"
kills.Parent = stats

plr.CharacterAdded:Connect(function(char)


    local humanoid

    repeat
        humanoid = char:FindFirstChild("Humanoid")
        wait()
    until humanoid

    humanoid.Died:connect(function()

        local tag = humanoid:FindFirstChild("creator")

        if tag then

            local killer = tag.Value

            if killer then

                killer.leaderstats.Kills.Value = killer.leaderstats.Kills.Value + 1

            end

        end

    end)

end)

end)

local Data = DataStore:GetAsync(Player.UserId)
if Data then
    kills.Value = Data

end game.Players.PlayerRemoving:Connect(function(Player) DataStore:SetAsync(Player.UserId, Player.leaderstats.Kills.Value) end)

Thanks!

0
the part where your trying to load the data actually put it into the 'playeradded' event function MarkedTomato 810 — 3y
0
also change the 'Player.UserId' to 'plr.UserId' in the loading data parameter MarkedTomato 810 — 3y
0
Please reformat your code. It looks like you've snipped part of the code so include the whole script. radiant_Light203 1166 — 3y

1 answer

Log in to vote
0
Answered by 3 years ago
Edited 3 years ago

datastore name has to be a string (and the players userid is a number) so you could do DataStore:SetAsync(tostring(player.UserId)) or DataStore:GetAsync(tostring(player.UserId))

You also want to get data before your character is added but after the player joins (right now it looks like your GetAsync is outside of the function with nothing defining the player). When you get data, you should also use plr.UserId instead of player.UserId because you put the var as plr in that function.

Ad

Answer this question