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

Data not saving while using DataStores. How do I fix?

How do i fix this script? When I leave and rejoin the data doesn't save.

local DataService = game:GetService("DataStoreService")
local DataStore = DataService:GetDataStore("DataStore")

game.Players.PlayerAdded:Connect(function(player)
	local leaderstats = Instance.new("Folder",player)
	leaderstats.Name = "leaderstats"
	local Credits = Instance.new("IntValue",leaderstats)
	Credits.Name = "Credits"
	
	local PlayerUserId = "Player"..player.UserId
	
	Credits.Value = DataStore:GetAsync(PlayerUserId)
end)

game.Players.PlayerRemoving:Connect(function(player)
	local PlayerUserId = "Player"..player.UserId
	local epics = player.leaderstats.Credits
	DataStore:SetAsync(PlayerUserId,epics.Value)
end)

1 answer

✓ Accepted answer

Hello there, it looks like you're not wrapping the DataStore in a pcall which is not so good. A pcall is basically a way that the code moves on if something doesn't work.

When you for example load or save data, it's usually important that you do that. I tried to redo your script and see if this could work.

	local DataService = game:GetService("DataStoreService")
	local DataStore = DataService:GetDataStore("DataStore")
	 
	game.Players.PlayerAdded:Connect(function(player)
	    local leaderstats = Instance.new("Folder",player)
	    leaderstats.Name = "leaderstats"
	    local Credits = Instance.new("IntValue",leaderstats)
    Credits.Name = "Credits"
	 
    local PlayerUserId = "Player"..player.UserId
	
local success, errormessage = pcall(function() 
    Credits.Value = DataStore:GetAsync(PlayerUserId)

end)
	end)
	 
	game.Players.PlayerRemoving:Connect(function(player)
	    local PlayerUserId = "Player"..player.UserId
	    local epics = player.leaderstats.Credits

local success, errormessage = pcall(function()
 DataStore:SetAsync(PlayerUserId,epics.Value)
end)
	end)

If this does not work, this might be some reasons why it might not work.

  • You've not published your game
  • You have not enabled in the game settings that studio can access datastores
  • You have used a wrong kind of script.

Those were some good advice and stuff I could help you with. Reply if it still doesn't work. Happy coding!

3 comments

0

Ah thanks, I'm pretty sure it works.

0

The only thing is that it only works when I go into server mode and change the stats there. When I use a clickdetector it doesn't save the data

0

Did you play and see if the datastore worked in studio or in the main game as it only works when you're in main game and not playing in studio.

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