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

DataStore won't save properly?

I made this script from a youtube tutorial on DataStores and I'm relatively new to scripting. I reviewed my script multiple times and see no errors but it won't work. I have my API on too btw.

`` local DataStoreService = game:GetService("DataStoreService") local myDataStore = DataStoreService:GetDataStore("myDataStore")

game.Players.PlayerAdded:Connect(function(player) local leaderstats = Instance.new("Folder") leaderstats.Name = "leaderstats" leaderstats.Parent = player

local Cash = Instance.new("IntValue")
Cash.Name = "Cash"
Cash.Parent = leaderstats

local playerUserId = "Player_"..player.UserId
-- Load Data

local data
local success, errormessage = pcall(function()
	data = myDataStore:GetAsync(playerUserId)
end)

if success then
	Cash.Value = data
	--Set our data equal to current cash
end

end)

game.Players.PlayerRemoving:Connect(function(player) local playerUserId = "Player_"..player.UserId

local data = player.leaderstats.Cash.Value

local success, errormessage = pcall(function()
	myDataStore:SetAsync(playerUserId, data)		
end)
if success then
	print("Data successfully saved")
else
	print("There was an error")
	warn(errormessage)
end

end) ``

1 answer

✓ Accepted answer

I understand that you want to make saving leaderstats? Here are better ones. A normal script inside of ServerScriptService - put NumberValues inside of it with the names of leaderstats you want to put in.

game.Players.PlayerAdded:connect(function(player)
local DataStore = game:GetService("DataStoreService")

	 local leader = Instance.new("Folder",player)
leader.Name = "leaderstats"

for i,v in pairs(script:GetChildren()) do 
local d = DataStore:GetDataStore(v.Name)
local x = Instance.new("NumberValue",leader)
x.Name = v.Name
x.Value = d:GetAsync(player.UserId) or v.Value



end
end)

game.Players.PlayerRemoving:Connect(function(player)
	for i,v in pairs(script:GetChildren()) do 
		print("Getting")
		local DataStore = game:GetService("DataStoreService")
		local d = DataStore:GetDataStore(v.Name)
		d:SetAsync(player.UserId, player.leaderstats[v.Name].Value)
		print("Saved")
	end
end)

1 comment

0

I tried this and it worked thank you!

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