I am making a leaderstats script with DataStores, and whenever I leave the game, the script throws an error, "attempted to index local 'player' (a nil value)". I have seen the forum posts throughout scripting helpers and other websites detailing how to fix this. I have tried these, and they work, but the players' data needs to save for the next time they join. We need the player to not be a nil value to save the data. How to fix? Thanks in advance! :D
The error occurs at line 32, and is later thrown to the console by line 39.
Code:
local DataStore = game:GetService("DataStoreService") local ds = DataStore:GetDataStore("PointsData") print("started") game.Players.PlayerAdded:Connect(function(player) local leaderstats = Instance.new("Folder", player) leaderstats.Name = "leaderstats" local points = Instance.new("IntValue",leaderstats) points.Name = "Points" local data local success, errormessage = pcall(function() data = ds:GetAsync(player.UserId.."-points") end) if success then print("got data") points.Value = data else print("could not get data") warn(errormessage) end end) game.Players.PlayerRemoving:Connect(function(player) local success, errormessage = pcall(function(player) ds:SetAsync(player.UserId.."-points",player.leaderstats.Points.Value) end) if success then print("Points saved successfully.") else print("Error saving data.") warn(errormessage) end end)