Tycoon loading and saving script using datastore

Hi. I just finished my Datastore script that saves and loads tycoons when ever a player leaves or joins. It works ok, but it still has a few bugs. For example. When I buy multiple droppers, they all go to the same place as the first one.

Heres my script:

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

local function Create_Table(plr)

	local ReturnTable = {} 
	
	local leaderstats_save = {
		plr.leaderstats.Cash.Value,
	}


	local Item_Table = {}

	for _, obj in ipairs(BoughtItems:GetChildren()) do 
		table.insert(Item_Table, obj.Name)
		obj:Destroy() 
	end

	table.insert(ReturnTable, leaderstats_save) 
	table.insert(ReturnTable, Item_Table) 

	return ReturnTable 

end

game.Players.PlayerAdded:Connect(function(plr)
	local Key = "id_"..plr.UserId
	local Data
	local success, err = pcall(function()
		Data = ds:GetAsync(Key)
	end)
	
	local CashLeader = plr.leaderstats.Cash

	if success and Data ~= nil then
		local LeaderstatTable = Data[1] 
		local ItemTable = Data[2] 

		local CashStat = LeaderstatTable[1]  

		CashLeader.Value = CashStat 

		for _, v in ipairs(ItemTable) do 
			if Items:FindFirstChild(v) then
				print(ItemTable)
				local LoadedModel = Items:FindFirstChild(v)
				LoadedModel:Clone().Parent = BoughtItems
			end		
		end
	end

end)

game.Players.PlayerRemoving:Connect(function(plr)
	local Key = "id_"..plr.UserId 
	local Table = Create_Table(plr)
	
	print(Key)

	local success, err = pcall(function() 
		ds:SetAsync(Key, Table) 
	end)

	if not success then 
		warn(err)
	else 
		print("Data Saved!")
	end

end)

What do you mean when you say they all go to the same place as the first one? As in they are all in the same Vector3 position?

yes, but I actually adjusted and fixed the script after I maid this.

1 Like

use CFrame:ToObjectSpace to fix if this is still an issue.

1 Like

I suggest instead of just warning about data save failures, attempt to retry the function instead of just throwing away all the players progress.

Also the same for data loading, if the data doesn’t load, you don’t retry or even kick them. Not sure entirely how your game functions but my guess would be any players that fail to have their data loaded will have their data overwritten when they leave.

Try adding some retry functions to salvage as much data as possible.

1 Like