Attempt to index nil with 'UserId' error

I’m currently making a datastore script and I keep getting this UserId error, I don’t know how else I would save data and I don’t know why this is causing an error. I overlooked it several times and didn’t find anything out of place.

How should I fix this?

Here is my script:

local dts = game:GetService("DataStoreService")
local creditstore = dts:GetDataStore("CreditStore")
local levelstore = dts:GetDataStore("LevelStore")

local players = game:GetService("Players")
local Player = players.LocalPlayer

local playerKey = Player.UserId --error

local data1
local data2

local function playerJoin(Player)
	local lds = Instance.new("Folder", Player)
	lds.Name = "leaderstats"
	
	local ps = Instance.new("Folder", Player)
	ps.Name = "stats"
	
	local level = Instance.new("IntValue", lds)
	level.Name = "Level"
	level.Value = 1
	
	local credits = Instance.new("IntValue", ps)
	credits.Name = "Credits"
	credits.Value = 500
	
	local success, errormessage = pcall(function()
		data1 = creditstore:GetAsync(playerKey)
		data2 = levelstore:GetAsync(playerKey)
	end)
	
	if success then
		credits.Value = data1
		level.Value = data2
	end
end

local function playerLeave()
	creditstore:SetAsync(playerKey, data1)
	levelstore:SetAsync(playerKey, data2)
end


players.PlayerAdded:Connect(playerJoin)
players.PlayerRemoving:Connect(playerLeave)

Thanks!

Something to know is that LocalPlayer is limited to per client, they refer to the player on the client and not any other players. Clearly that’s not how you should get the key, but you want to use Player.UserId immediately and discard the playerKey and first Player variable.

Script

local dts = game:GetService("DataStoreService")
local creditstore = dts:GetDataStore("CreditStore")
local levelstore = dts:GetDataStore("LevelStore")

local players = game:GetService("Players")

local data1
local data2

local function playerJoin(player)
	local lds = Instance.new("Folder", player)
	lds.Name = "leaderstats"
	
	local ps = Instance.new("Folder", player)
	ps.Name = "stats"
	
	local level = Instance.new("IntValue", lds)
	level.Name = "Level"
	level.Value = 1
	
	local credits = Instance.new("IntValue", ps)
	credits.Name = "Credits"
	credits.Value = 500
	
	local success, errormessage = pcall(function()
		data1 = creditstore:GetAsync(player.UserId)
		data2 = levelstore:GetAsync(player.UserId)
	end)
	
	if success then
		credits.Value = data1
		level.Value = data2
	end
end

local function playerLeave(player)
	creditstore:SetAsync(player.UserId, data1)
	levelstore:SetAsync(player.UserId, data2)
end


players.PlayerAdded:Connect(playerJoin)
players.PlayerRemoving:Connect(playerLeave)
4 Likes

Thanks for the info and the speedy reply, much appreciated.