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

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

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!

3 comments

0

the part where your trying to load the data actually put it into the 'playeradded' event function

0

also change the 'Player.UserId' to 'plr.UserId' in the loading data parameter

0

Please reformat your code. It looks like you've snipped part of the code so include the whole script.

1 answer

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.

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