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

How can I make this datastore script work properly?

In my game I am adding hats for players to collect and wear as trophies for the achievements they make in the game, but the script I made to save the hats has lots of flaws in it that I don't know how to fix, the main one being how to save several bits of data without going over the place limit. Any help with this would be greatly appreciated here is the script that I'm having trouble with:

local DataStoreService = game:GetService("DataStoreService")
local Players = game:GetService("Players")
local num = 0
 
local function onPlayerAdded(player)
	local scope = "player_" .. player.UserId
	local HatSource = DataStoreService:GetDataStore("Hats", scope)
	local folder = game.ServerStorage["Hat List"]:clone()
	folder.Parent = player
	
	
	repeat
	num = num + 1
	print(num)
	local hatid = folder["id"..num]
	
	folder.id1.Value = HatSource:GetAsync(player.UserId) or false
	until num == 8
	num = 0
	
	local hatid = folder.id1
	hatid.Changed:connect(function()
		print('Saving Data')
		HatSource:SetAsync(player.UserId,hatid.Value)		
	end)
	
end
Players.PlayerAdded:Connect(onPlayerAdded)

1 answer

✓ Accepted answer

The main issue was you were treating GetDataStore() as GetAsync or SetAsync which isn't how you treat it.

local DataStoreService = game:GetService("DataStoreService")
local Players = game:GetService("Players")
local HatSource = DataStoreService:GetDataStore("Hats")
local num = 0

local function onPlayerAdded(player)
    local scope = "player_" .. player.UserId
    local folder = game.ServerStorage["Hat List"]:Clone()
    folder.Parent = player


    repeat
    num = num + 1
    print(num)
    local hatid = folder["id"..num]
	pcall(function()
    folder.id1.Value = HatSource:GetAsync(player.UserId) or false -- Not a good idea to have a repeat should atleast encase it with pcall
	end)
    until num == 8
    num = 0

    local hatid = folder.id1
    hatid.Changed:connect(function()
        print('Saving Data')
        HatSource:SetAsync(player.UserId,hatid.Value)       
    end)

end
Players.PlayerAdded:Connect(onPlayerAdded)

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