Hello,
I’m working on my tycoon game but I can’t seem to get the data saving to work properly (only the buttons to rebuy the items show and it also lags a lot). I’ve tried everything I could. Here’s the script as of right now (the amount of cash the player has is saved inside the leaderstats script already):
local DataStoreService = game:GetService("DataStoreService")
local Players = game:GetService("Players")
local Workspace = game:GetService("Workspace")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local datastore = DataStoreService:GetDataStore("TycoonItemData")
local function saveData(player)
local purchases = {}
local tycoon = Workspace.Tycoons:FindFirstChild(player:FindFirstChild("TycoonOwned").Value) or nil
if tycoon then
for _, v in pairs(tycoon.Purchases:GetChildren()) do
table.insert(purchases, v.Name)
end
local data = {
Cash = tycoon.Values.MoneyValue.Value,
Purchases = purchases
}
local success, errorMessage = pcall(function()
datastore:SetAsync(tostring(player.UserId), data)
end)
if success then
else
warn("Failed to save data for player", player.UserId, errorMessage)
end
else
warn("Tycoon not found for player", player.UserId)
end
end
local function loadData(player, tycoon)
local success, data = pcall(function()
return datastore:GetAsync(tostring(player.UserId))
end)
if success then
if data then
for _, item in pairs(data.Purchases) do
local itemInReplicatedStorage = ReplicatedStorage.Tycoon.PurchasedItems:FindFirstChild(item)
if itemInReplicatedStorage then
local cloneItem = itemInReplicatedStorage:Clone()
cloneItem.Parent = tycoon.Purchases
else
warn("Item not found in ReplicatedStorage:", item)
end
end
tycoon.Values.MoneyValue.Value = data.Cash
else
end
else
warn("Failed to load data for player", player.UserId, data)
end
end
Players.PlayerRemoving:Connect(saveData)
game:BindToClose(function()
for _, player in ipairs(Players:GetPlayers()) do
saveData(player)
end
end)
Players.PlayerAdded:Connect(function(player)
local tycoonOwned = Instance.new("StringValue")
tycoonOwned.Name = "TycoonOwned"
tycoonOwned.Parent = player
player.TycoonOwned.Changed:Connect(function()
local tycoonName = player.TycoonOwned.Value
if tycoonName then
local tycoon = Workspace.Tycoons:FindFirstChild(tycoonName)
if tycoon then
loadData(player, tycoon)
end
end
end)
end)
Workspace.Tycoons.ClaimTycoon.Event:Connect(function(player, tycoon)
if player:IsA("Player") and tycoon:IsA("Model") then
player.TycoonOwned.Value = tycoon.Name
loadData(player, tycoon)
else
warn("Invalid arguments passed to ClaimTycoon event")
end
end)
Here’s the hierarchy of a template tycoon in ReplicatedStorage: