Here is the error message and my line of code ServerScriptService.leaderstats:40: attempt to index nil with 'leaderstats' - Server - leaderstats local clicksValue = player.leaderstats.Clicks.Value
You didn't load the data from the Data Store using DataStore:GetAsync()
. I recommend using DataStore:UpdateAsync()
instead of DataStore:SetAsync()
, but you should never use DataStore:UpdateAsync()
when you're using a leaderboard or OrderedDataStore
. I made some changes and added new stuff to ensure your data is safe and working.
local Players = game:GetService("Players") local runService = game:GetService("RunService") local dataStoreService = game:GetService("DataStoreService") local clicksDataStore = dataStoreService:GetDataStore("Clicks") local function waitForRequestBudget(requestType) local currentBudget = dataStoreService:GetRequestBudgetForRequestType(requestType) while currentBudget < 1 do currentBudget = dataStoreService:GetRequestBudgetForRequestType(requestType) task.wait(5) end end function loadData(player) local playerUserId = "player_" .. player.UserId local leaderstats = Instance.new("Folder", player) leaderstats.Name = "leaderstats" local clicks = Instance.new("IntValue", leaderstats) clicks.Name = "Clicks" local success, result repeat waitForRequestBudget(Enum.DataStoreRequestType.GetAsync) success, result = pcall(clicksDataStore.GetAsync, clicksDataStore, playerUserId) until (success and result) or (not Players:FindFirstChild(player.Name)) clicks.Value = result or 0 end function saveData(player, dontWait) local playerUserId = "player_" .. player.UserId local leaderstats = player:FindFirstChild("leaderstats") local clicks = leaderstats:FindFirstChild("Clicks") local success, err repeat if not donWait then waitForRequestBudget(Enum.DataStoreRequestType.UpdateAsync) end success, err = pcall(clicksDataStore.UpdateAsync, clicksDataStore, playerUserId, function() return clicks.Value end) until success end for _, player in ipairs(Players:GetPlayers()) do coroutine.wrap(loadData)(player) end Players.PlayerAdded:Connect(loadData) -- when the player joins Players.PlayerRemoving:Connect(saveData) -- when the player leavs game:BindToClose(function() -- when the game is shutting down if runService:IsStudio() then task.wait(2) else local finished = Instance.new("BindableEvent") local allPlayers = Players:GetPlayers() local leftPlayers = #allPlayers for _, player in ipairs(allPlayers) do coroutine.wrap(function() saveData(player, true) leftPlayers -= 1 if leftPlayers == 0 then finished:Fire() end end)() end finished.Event:Wait() end end)
This script is based from this DevForum post.