How do I save a Folder with datastore

So I am making a tycoon game and I want to save the users purchases like when they buy a dropper or a conveyor belt, etc. So basically I just want to save the stuff which is inside this folder when they leave and load it back in when they claim a tycoon.

Electronics Tycoon BoughtItems Folder

this is my datastore script as of now

local ds = game:GetService("DataStoreService"):GetDataStore("SaveData")
local BoughtItems = game.Workspace.Groups.TycoonModel.BoughtItems
BoughtItems = {}

game.Players.PlayerAdded:Connect(function(plr)
	wait()
	local plrkey = "id_"..plr.UserId
	local save1 = plr.leaderstats.Cash
	local save2 = plr.leaderstats.Rebirths

	local GetSaved = ds:GetAsync(plrkey)
	if GetSaved then
		save1.Value = GetSaved[1]
		save2.Value = GetSaved[2]
	else
		local NumberForSaving = {save1.Value, save2.Value}
		ds:GetAsync(plrkey, NumberForSaving)
	end
end)

game.Players.PlayerRemoving:Connect(function(plr)
	ds:SetAsync("id_"..plr.UserId, {plr.leaderstats.Cash.Value, plr.leaderstats.Rebirths.Value})
end)

Thanks
The Spikey Man

1 Like

DataStores can only be used to store primitive value types, think booleans, tables, strings, numbers etc. not instance or collections of instances, however I was able to come up with a quick on the fly hack.

You could use a single DataStore, with scopes which would represent the individual models & then have table values assigned to the keys of those unique scopes which represent the properties of the collection of parts within the separate models.

Idk datastore that much (I just followed a tutorial)

Here’s a recently made resource which may help do this automatically for you:

1 Like

can you pls say this in an easier english (I dont have that good english)

The way you would do this is by using the datastore service and looping though the items in the folder inserting them into a table using name which you could save to a datastore and then when loading loop though the loaded table and clone the items based on name.

Code example
--[[
for _, v in pairs(workspace:GetDescendants()) do
	if v:IsA("BillboardGui") then
		v.MaxDistance = 60
	end
end
--]]

-- Services
local DataStoreService = game:GetService("DataStoreService")
local WorkSpace = game:GetService("Workspace")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local DataStore = DataStoreService:GetDataStore("GameData_VS1")

local DataModule = {}

function CreateDataTable(player, PlayerTycoonNumber)
	
	local TycoonFolder = WorkSpace:FindFirstChild("Tycoons")
	local Tycoon = TycoonFolder:FindFirstChild("Tycoon"..PlayerTycoonNumber)
	
	-- leaderstats
	local leaderstats = player:WaitForChild("Leaderstats")
	local CashValue = leaderstats:FindFirstChild("Cash")
	local Code1Value = leaderstats:FindFirstChild("Code1")
	
	local Code1Val = "false"
	if Code1Value.Value == true then
		Code1Val = "True"
	end
	
	local MainDataTable = {}
	local leaderstatTable = {
		CashValue.Value,
		Code1Val
	}
	local ItemTable = {}
	
	local BroughtItems = Tycoon:WaitForChild("BoughtItems")
	
	-- Saving Items
	for _, v in ipairs(BroughtItems:GetChildren()) do
		table.insert(ItemTable, v.Name)
		v:Destroy()
	end
	
	table.insert(MainDataTable, leaderstatTable)
	table.insert(MainDataTable, ItemTable)
	
	return MainDataTable
	
end

function DataModule:Save(player, PlayerTycoonNumber)
	
	local GetTables = CreateDataTable(player, PlayerTycoonNumber)
	local DataKey = player.UserId.."-GameData_Version.1.0.0"
	
	local success, err = pcall(function()
		DataStore:SetAsync(DataKey, GetTables)
	end)
	
	if not success then print(err) end
	if success then print("Success") end
	
end

function DataModule:LoadData(player, PlayerTycoonNumber)
	
	local DataKey = player.UserId.."-GameData_Version.1.0.0"
	local LoadedData
	
	local success, err = pcall(function()
		LoadedData = DataStore:GetAsync(DataKey)
	end)
	
	if success then print("Success") end
	if not success then warn(err) end
	
	if LoadedData then
		print("Got Data")
		local leaderstatsData = LoadedData[1]
		local ItemData = LoadedData[2]
		
		-- Leaderstats
		local leaderstats = player:FindFirstChild("Leaderstats")
		local CashValue = leaderstats:FindFirstChild("Cash")
		local Code1Value = leaderstats:FindFirstChild("Code1")
		
		CashValue.Value = leaderstatsData[1]
		if leaderstatsData[2] == "true" then
			Code1Value.Value = true
		end
		
		local TycoonFolderClone = ReplicatedStorage:FindFirstChild("Tycoon"..PlayerTycoonNumber)
		local TycoonFolder = WorkSpace:FindFirstChild("Tycoons"):FindFirstChild("Tycoon"..PlayerTycoonNumber)
		
		-- Item
		for i, obj in ipairs(ItemData) do
			
			if TycoonFolderClone.BoughtItems:FindFirstChild(obj) then
				local LoadedModel = TycoonFolderClone.BoughtItems:FindFirstChild(obj):Clone()
					
				if LoadedModel then
					LoadedModel.Parent = TycoonFolder.BoughtItems	
				else		
					LoadedModel = nil
					return		
				end
			end
			
			
		end
		
	else
		print("No Data")
	end
	
end

local function Auto(player, PlayerTycoonNumber)
	while true do
		wait(60) -- Auto Saves A Player Every Minute
		DataModule:Save(player, PlayerTycoonNumber)
		print("Auto Saving...")
	end
end
	
function DataModule:AutoSave(player, PlayerTycoonNumber)
	print("Auto Save Started...")
	Auto(player, PlayerTycoonNumber)
end

return DataModule
4 Likes

I will check that now, Thank You!

pls give me a code example so I can understand it better

If you have no knowledge of code or where to begin I wouldn’t suggest attempting a project as ambitious as this.

1 Like

Its in my original post, you will however need to modify it to make it work in your situation.

Your kinda right, but I have been working on my game since 2 months that is y I just want to finish it

why is this commented? and what does it do

Fair enough, take a look at the code which was provided to you & the resource which I provided above, if you search “datastore instances” or “datastore folders” etc. you’ll find more related threads too.

Oh, thats unrelated, I was using this in my tycoon game for something else, please ignore that.

Ok thanks for your help and thank u apoaddda(kinda hard username) for your help too.
what do I do now?

I am currently writing you a coding example which should work in your situation, it should be done shortly.

btw apoaddda we have same profile picture just kinda of different

ooo thank u apoaddda thank u soo much

You can save the name of all the models in a table, and when you’re retrieving the data, you can loop through the table and clone all the needed droppers back into the folder. In this case, you’d have store the tycoon items in ServerStorage.

Code:

local DataStoreService = game:GetService("DataStoreService")
local TycoonDataStore = DataStoreService:GetDataStore("TycoonDataStore ")

game.PlayerAdded(function(player)
    local folder = game.Workspace.BoughtItems
    local data

    local success, errormessage = pcall(function()
        data = TycoonDataStore:GetAsync(player.UserId)
    end)

   if success then
      for i, v in pairs(data) do
         local dropper = game.ServerStorage:FindFirstChild(v)
         dropper.Parent = folder
      end
   end
end)

game.PlayerRemoving:Connect(function(player)
    local folder = game.Workspace.BoughtItems
    local data
    
    for i, v in pairs(folder:GetChildren()) do
       table.insert(data, v.Name)
    end

    local success, errormessage = pcall(function()
        TycoonDataStore:SetAsync(player.UserId, data)
    end)
end)
1 Like

This is some code that should work, the only variable you have to change should be the Items one which would need to be where the tycoon items are stored when the player doesn’t own them.

local ds = game:GetService("DataStoreService"):GetDataStore("SaveData")
local Items = pathtoitem -- Where the items are located ie game:GetService("ReplicatedStorage").TycoonItems
local BoughtItems = game.Workspace.Groups.TycoonModel.BoughtItems

local function Create_Table(plr)

	local ReturnTable = {} -- Returns the table
	-- Creates the leaderstats table
	local leaderstats_save = {
		plr.leaderstats.Cash.Value,
		plr.leaderstats.Rebirths.Value
	}


	local Item_Table = {}

	for _, obj in ipairs(BoughtItems:GetChildren()) do -- This loops through the folder where the player owns the items
		table.insert(Item_Table, obj.Name)
		obj:Destroy() -- this will remove the item once it is inserted into the table
	end

	table.insert(ReturnTable, leaderstats_save) -- Inserts the first sub table
	table.insert(ReturnTable, Item_Table) -- Inserts the second sub table

	return ReturnTable -- Returns 1 table containing two sub tables to the save script

end

game.Players.PlayerAdded:Connect(function(plr)
	local Key = "id_"..plr.UserId
	local Data
	local success, err = pcall(function() -- I put this into a pcall function to handle errors
		Data = ds:GetAsync(Key)
	end)
	-- Stats locating
	local CashLeader = plr.leaderstats.Cash
	local RebirthLeader = plr.leaderstats.Rebirths

	if success and Data ~= nil then
		local LeaderstatTable = Data[1] -- Getting sub tables
		local ItemTable = Data[2] -- Getting sub tables

		local CashStat = LeaderstatTable[1] -- Getting the cash value
		local RebirthStat = LeaderstatTable[2] -- Getting the leaderstats value

		CashLeader.Value = CashStat -- Setting the stat values
		RebirthLeader.Value = RebirthStat -- Setting the stat values

		for _, v in ipairs(ItemTable) do -- Looping through the loaded table checking for the item
			if Items:FindFirstChild(v) then
				local LoadedModel = Items:FindFirstChild(v)
				LoadedModel:Clone().Parent = BoughtItems -- Cloning the loaded model
			end		
		end
	end

end)

game.Players.PlayerRemoving:Connect(function(plr)
	local Key = "id_"..plr.UserId -- Data key
	local Table = Create_Table(plr) -- Call the function with parameter
	
	local success, err = pcall(function() -- This function handles errors
		ds:SetAsync(Key, Table) -- Saving to the data store
	end)
	
	if not success then -- if saving failed it will warn the error in the output.
		warn(err)
	end
	
end)
4 Likes