so i have a leaderstat called Coins and no matter what it will not save and i have no idea what it is doing
I take it that this is a server script?
You can’t access game.Players.LocalPlayer
from a server script, so I would recommend making user of game.Players.PlayerAdded
to get the player objects of users as soon as they join, then handle each player seperately.
Additionally, you can’t save an instance in a datastore like you are attempting to do, so you will need to save the specific values held within the leaderstat instead (e.g. the number itself).
The Players.LocalPlayer
property is only for LocalScripts
. You are attempting on getting it on a ServerScript
.
Code changes:
- local player = game.Players.LocalPlayer
+ local players = game.Players
local dataStore = game:GetService("DataStoreService"):GetDataStore("PlayerProgress")
-- Function to save player progress
- local function saveProgress()
+ local function saveProgress(player)
local key = player.UserId
local success, err = pcall(function()
dataStore:SetAsync(key, player.leaderstats)
end)
if not success then
warn("Failed to save player progress: "..err)
end
end
- player.CharacterAdded:Connect(saveProgress)
-- Connect the player's leaving event to save progress
+ players.PlayerAdded:Connect(function(player)
+ player.CharacterRemoving:Connect(saveProgress)
+ end)
-- Save progress when the game is closed
- game:BindToClose(saveProgress)
+ game:BindToClose(function()
+ for _, player in pairs(players:GetChildren()) do
+ saveProgress(player)
+ end
+ end)
Also, you’re saving the progress when the player joins, not when they leave, therefore it will cause an error. I also fixed the problem.
Actual code:
local players = game.Players
local dataStore = game:GetService("DataStoreService"):GetDataStore("PlayerProgress")
-- Function to save player progress
local function saveProgress(player)
local key = player.UserId
local success, err = pcall(function()
dataStore:SetAsync(key, player.leaderstats)
end)
if not success then
warn("Failed to save player progress: "..err)
end
end
players.PlayerAdded:Connect(function(player)
-- Connect the player's leaving event to save progress
player.CharacterRemoving:Connect(saveProgress)
end)
-- Save progress when the game is closed
game:BindToClose(function()
for _, player in pairs(players:GetChildren()) do
saveProgress(player)
end
end)
im gettinng this error when i use your script
Whoops! I meant to use Player.CharacterRemoving
. I’ll update my post.
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.