ok so when i add a tool into starterpack, it breaks my whole tool saving script. This is…
- User
ok so when i add a tool into starterpack, it breaks my whole tool saving script. This is my script that handles the saving: --🔁 FINALIZED RESTOCK SYSTEM WITH INSTANT TIMER RESET AND SYNC --
local DataStoreService = game:GetService("DataStoreService") local MessagingService = game:GetService("MessagingService") local Players = game:GetService("Players") local ReplicatedStorage = game:GetService("ReplicatedStorage") local MarketplaceService = game:GetService("MarketplaceService") local WorkersFolder = game:GetService("ReplicatedStorage"):WaitForChild("Workers")
local updateTimerEvent = ReplicatedStorage:WaitForChild("UpdateRestockTimer") local updateStockEvent = ReplicatedStorage:WaitForChild("UpdateItemStock") local notifyRestockEvent = ReplicatedStorage:WaitForChild("NotifyRestock") local buyCashEvent = ReplicatedStorage:WaitForChild("BuyWithCash") local buyRobuxEvent = ReplicatedStorage:WaitForChild("BuyWithRobux") local canBuyRestockFunction = ReplicatedStorage:WaitForChild("CanBuyRestock") local placementEvent = ReplicatedStorage:WaitForChild("StartPlacingWorker")
local globalStockStore = DataStoreService:GetDataStore("GlobalStockData") local playerStockStore = DataStoreService:GetDataStore("PlayerStockData") local workerSaveStore = DataStoreService:GetDataStore("WorkerSaveData") local toolSaveStore = DataStoreService:GetDataStore("SavedTools") local placedWorkersStore = DataStoreService:GetDataStore("PlacedWorkers")
local RESTOCK_TOPIC = "GlobalRestockSignal" local LEADER_LOCK_KEY = "RestockLeaderLock" local RESTOCK_INTERVAL = 60 -- 5 minutes local HEARTBEAT_INTERVAL = 1 local LOCK_EXPIRY = 2
local globalStock = {} local playerStocks = {} local timeLeft = RESTOCK_INTERVAL local isLeader = false
local itemRarity = { BurgerFlipper = "Rare", LazyWorker = "Common", }
local rarityStockRanges = { Common = {4, 6}, Uncommon = {2, 3}, Rare = {1, 3}, Legendary = {1, 2}, Mythical = {1, 1}, Divine = {1, 1}, }
local rarityRestockChance = { Common = 100, Uncommon = 100, Rare = 60, Legendary = 35, Mythical = 7.5, Divine = 1, }
local devProductIds = { BurgerFlipper = 12345678, LazyWorker = 23456789, PersonalRestock = 3333200727, }
-- Get current timestamp local function getTimestamp() return os.time() end
-- Acquire leadership if expired local function tryAcquireLeadership() local now = getTimestamp() local success, lock = pcall(function() return globalStockStore:GetAsync(LEADER_LOCK_KEY) end)
if success then if not lock or (now - (lock.timestamp or 0)) > LOCK_EXPIRY then local newLock = { timestamp = now, serverId = game.JobId } local setSuccess = pcall(function() globalStockStore:SetAsync(LEADER_LOCK_KEY, newLock) end) return setSuccess end end return falseend
local function sendHeartbeat() pcall(function() globalStockStore:SetAsync(LEADER_LOCK_KEY, { timestamp = getTimestamp(), serverId = game.JobId }) end) end
local function generateStock() local stock = {} for itemName, rarity in pairs(itemRarity) do if math.random(1, 100) <= (rarityRestockChance[rarity] or 100) then local range = rarityStockRanges[rarity] stock[itemName] = math.random(range[1], range[2]) else stock[itemName] = 0 end end return stock end
local function applyStock(newStock) globalStock = newStock local version = getTimestamp()
pcall(function() globalStockStore:SetAsync("Stock", globalStock) globalStockStore:SetAsync("RestockVersion", version) globalStockStore:SetAsync("RestockTimer", RESTOCK_INTERVAL) end) for player, _ in pairs(playerStocks) do playerStocks[player] = {} for itemName, amount in pairs(globalStock) do playerStocks[player][itemName] = amount end pcall(function() playerStockStore:SetAsync(tostring(player.UserId), { Stock = playerStocks[player], Version = version, }) end) for itemName, amount in pairs(playerStocks[player]) do updateStockEvent:FireClient(player, itemName, amount) end end for _, player in ipairs(Players:GetPlayers()) do notifyRestockEvent:FireClient(player) endend
local function broadcastRestock(stock) pcall(function() MessagingService:PublishAsync(RESTOCK_TOPIC, { stock = stock, time = RESTOCK_INTERVAL, }) end) end
local function subscribeToRestock() pcall(function() MessagingService:SubscribeAsync(RESTOCK_TOPIC, function(message) local data = message.Data if typeof(data) == "table" and data.stock and data.time then applyStock(data.stock) timeLeft = data.time end end) end) end
local function initialize() subscribeToRestock()
local ok, stock = pcall(function() return globalStockStore:GetAsync("Stock") end) if ok and stock then globalStock = stock else globalStock = generateStock() end local ok2, timer = pcall(function() return globalStockStore:GetAsync("RestockTimer") end) timeLeft = ok2 and timer or RESTOCK_INTERVALend
local function run() initialize() while true do isLeader = tryAcquireLeadership()
if isLeader then local accumulator = 0 while timeLeft > 0 do local dt = task.wait(0.1) accumulator += dt if accumulator >= 1 then timeLeft -= 1 accumulator -= 1 updateTimerEvent:FireAllClients(timeLeft) pcall(function() globalStockStore:SetAsync("RestockTimer", timeLeft) end) sendHeartbeat() end end local newStock = generateStock() applyStock(newStock) broadcastRestock(newStock) timeLeft = RESTOCK_INTERVAL -- reset instantly else task.wait(1) end endend
task.spawn(run)
local personalRestockCooldowns = {}
local function restockPlayerShop(player) if not player then return end
-- Cooldown check local lastRestock = personalRestockCooldowns[player.UserId] or 0 if os.clock() - lastRestock < 5 then warn("[Restock] Player attempted to restock too quickly:", player.Name) return end personalRestockCooldowns[player.UserId] = os.clock() -- Generate and apply new personal stock local newStock = {} for itemName, rarity in pairs(itemRarity) do if math.random(1, 100) <= (rarityRestockChance[rarity] or 100) then local range = rarityStockRanges[rarity] newStock[itemName] = math.random(range[1], range[2]) else newStock[itemName] = 0 end end playerStocks[player] = newStock for itemName, amount in pairs(newStock) do updateStockEvent:FireClient(player, itemName, amount) end pcall(function() playerStockStore:SetAsync(tostring(player.UserId), { Stock = newStock, Version = os.time(), }) end)end
Players.PlayerAdded:Connect(function(player) print("[DEBUG] PlayerAdded fired for", player.Name) local restockVersion = 0 pcall(function() restockVersion = globalStockStore:GetAsync("RestockVersion") or 0 end)
local savedStock, savedVersion = nil, 0 pcall(function() local data = playerStockStore:GetAsync(tostring(player.UserId)) if type(data) == "table" then savedStock = data.Stock savedVersion = data.Version or 0 end end) if not savedStock or savedVersion < restockVersion then playerStocks[player] = {} for itemName, amount in pairs(globalStock) do playerStocks[player][itemName] = amount end else playerStocks[player] = savedStock end for itemName, amount in pairs(playerStocks[player]) do updateStockEvent:FireClient(player, itemName, amount) end local toolsData pcall(function() toolsData = toolSaveStore:GetAsync("Tools_" .. player.UserId) end) print("Loaded tools for", player.Name, ":", toolsData) local toolsData local successTools, errTools = pcall(function() toolsData = toolSaveStore:GetAsync("Tools_" .. player.UserId) end) if successTools and typeof(toolsData) == "table" then for _, workerName in ipairs(toolsData) do local workerModel = WorkersFolder:FindFirstChild(workerName) if workerModel then local tool = Instance.new("Tool") tool.Name = workerName tool.RequiresHandle = false local clone = workerModel:Clone() clone.Name = "WorkerModel" clone.Parent = tool -- Include AnimationId if exists local animId = clone:FindFirstChild("AnimationId") if animId and animId:IsA("StringValue") then local animCopy = animId:Clone() animCopy.Parent = tool end tool.Parent = player:WaitForChild("Backpack") end end print("[DEBUG] Loaded tools for", player.Name) elseif not successTools then warn("[ERROR] Failed to load tools for", player.Name, ":", errTools) end -- 🏗️ Restore Placed Workers local placedData local successPlaced, errPlaced = pcall(function() placedData = placedWorkersStore:GetAsync("Placed_" .. player.UserId) end) print("📦 Loaded PlacedData for", player.Name, ":", placedData) if successPlaced and typeof(placedData) == "table" then local plotName = player:GetAttribute("AssignedPlot") local plot = workspace.Plots:FindFirstChild(plotName) if plot then local base = plot:FindFirstChild("Base") if base then for _, workerInfo in ipairs(placedData) do local modelName = workerInfo.Name local cfData = workerInfo.CFrame local modelTemplate = WorkersFolder:FindFirstChild(modelName) if modelTemplate and typeof(cfData) == "table" then local clone = modelTemplate:Clone() if clone.PrimaryPart then local loadedCFrame = CFrame.new( cfData.x, cfData.y, cfData.z, cfData.r00, cfData.r01, cfData.r02, cfData.r10, cfData.r11, cfData.r12, cfData.r20, cfData.r21, cfData.r22 ) clone:SetPrimaryPartCFrame(loadedCFrame) end local anim = clone:FindFirstChildWhichIsA("Animation", true) local humanoid = clone:FindFirstChildWhichIsA("Humanoid") if anim and humanoid then local animationTrack = humanoid:LoadAnimation(anim) animationTrack:Play() end local placedFlag = Instance.new("BoolValue") placedFlag.Name = "IsPlaced" placedFlag.Value = true placedFlag.Parent = clone clone.Parent = base print("[DEBUG] Loaded placed worker:", modelName) else warn("[WARN] No worker model found or missing CFrame for:", modelName) end end else warn("[WARN] No Base part found in plot "..plotName) end else warn("[WARN] No plot found for player "..player.Name) end elseif not successPlaced then warn("[ERROR] Failed to load placed workers for", player.Name, ":", errPlaced) endend)
Players.PlayerRemoving:Connect(function(player) print("[DEBUG] PlayerRemoving fired for", player.Name) local userId = player.UserId
-- Save player stock local stock = playerStocks[player] if stock then pcall(function() playerStockStore:SetAsync(tostring(userId), { Stock = stock, Version = getTimestamp() }) end) playerStocks[player] = nil end -- Save tools in backpack local toolNames = {} local backpack = player:FindFirstChild("Backpack") if backpack then for _, item in ipairs(backpack:GetChildren()) do if item:IsA("Tool") then table.insert(toolNames, item.Name) end end end print("[DEBUG] Saving tools for", player.Name, ":", toolNames) pcall(function() toolSaveStore:SetAsync("Tools_" .. userId, toolNames) end) -- Save placed workers inside the player's Base local placedInfo = {} local plotName = player:GetAttribute("AssignedPlot") local plot = workspace.Plots:FindFirstChild(plotName) if plot then local base = plot:FindFirstChild("Base") if base then for _, obj in ipairs(base:GetChildren()) do if obj:IsA("Model") then print("🔍 Found model:", obj.Name) local hasPlacedFlag = obj:FindFirstChild("IsPlaced") local hasPrimary = obj.PrimaryPart ~= nil if hasPlacedFlag and hasPrimary then local cframe = obj.PrimaryPart.CFrame local x, y, z, r00, r01, r02, r10, r11, r12, r20, r21, r22 = cframe:GetComponents() table.insert(placedInfo, { Name = obj.Name, CFrame = { x = x, y = y, z = z, r00 = r00, r01 = r01, r02 = r02, r10 = r10, r11 = r11, r12 = r12, r20 = r20, r21 = r21, r22 = r22, } }) print("📌 Worker saved:", obj.Name, "at", obj.PrimaryPart.Position) end end end else warn("[WARN] No Base part found in plot "..plotName) end else warn("[WARN] No plot found for player "..player.Name) end print("📝 Saving PlacedInfo for", player.Name, ":", placedInfo) local success, err = pcall(function() placedWorkersStore:SetAsync("Placed_" .. player.UserId, placedInfo) end) if success then print("[DEBUG] Successfully saved placed workers for", player.Name) else warn("[ERROR] Failed to save placed workers:", err) endend)
buyCashEvent.OnServerEvent:Connect(function(player, itemName, price) local stats = player:FindFirstChild("leaderstats") local cash = stats and stats:FindFirstChild("Cash") if not cash or not tonumber(price) then return end
local stock = playerStocks[player] if not stock or (stock[itemName] or 0) <= 0 then updateStockEvent:FireClient(player, itemName, 0) return end if cash.Value < tonumber(price) then return end -- ✅ Deduct cash and stock cash.Value -= tonumber(price) stock[itemName] -= 1 updateStockEvent:FireClient(player, itemName, stock[itemName]) -- ✅ Give worker tool local workerModel = WorkersFolder:FindFirstChild(itemName) if workerModel then local tool = Instance.new("Tool") tool.Name = itemName tool.RequiresHandle = false -- 📦 Store the model inside the tool for placement local workerClone = workerModel:Clone() workerClone.Name = "WorkerModel" workerClone.Parent = tool -- Optional: Store animation ID for UI preview if needed local animationId = workerClone:FindFirstChild("AnimationId") if animationId and animationId:IsA("StringValue") then local animCopy = animationId:Clone() animCopy.Parent = tool end -- 📤 Place tool in player's backpack tool.Parent = player:WaitForChild("Backpack") endend)
canBuyRestockFunction.OnServerInvoke = function(player) local lastRestock = personalRestockCooldowns[player.UserId] or 0 return os.clock() - lastRestock >= 5 end
MarketplaceService.ProcessReceipt = function(receipt) local player = Players:GetPlayerByUserId(receipt.PlayerId) if not player then return Enum.ProductPurchaseDecision.NotProcessedYet end
for itemName, id in pairs(devProductIds) do if id == receipt.ProductId then if itemName == "PersonalRestock" then restockPlayerShop(player) else updateStockEvent:FireClient(player, itemName, math.huge) end break end end return Enum.ProductPurchaseDecision.PurchaseGrantedend
Assistant
Ah, I see the issue! The problem is that your tool saving system is saving all tools in the player's backpack, including the hammer tool you added to
StarterPack. When the player rejoins, the script tries to load these tools, but the hammer tool (which is automatically given viaStarterPack) conflicts with the saved tools.Solution: Exclude the Hammer Tool from Saving
We need to modify your
PlayerRemovingandPlayerAddedlogic to ignore the hammer tool when saving/loading tools.1. Modify
PlayerRemovingto Skip the Hammer ToolIn your
Players.PlayerRemoving:Connectfunction, update the tool-saving logic to exclude the hammer:-- Save tools in backpack (excluding the hammer) local toolNames = {} local backpack = player:FindFirstChild("Backpack") if backpack then for _, item in ipairs(backpack:GetChildren()) do if item:IsA("Tool") and item.Name ~= "Hammer" then -- Skip the hammer tool table.insert(toolNames, item.Name) end end end2. Modify
PlayerAddedto Avoid Loading the HammerIn your
Players.PlayerAdded:Connectfunction, ensure the hammer isn't loaded from saved data (since it's already given viaStarterPack):-- Load tools (excluding the hammer) local toolsData local successTools, errTools = pcall(function() toolsData = toolSaveStore:GetAsync("Tools_" .. player.UserId) end) if successTools and typeof(toolsData) == "table" then for _, workerName in ipairs(toolsData) do if workerName ~= "Hammer" then -- Skip the hammer tool local workerModel = WorkersFolder:FindFirstChild(workerName) if workerModel then local tool = Instance.new("Tool") tool.Name = workerName tool.RequiresHandle = false local clone = workerModel:Clone() clone.Name = "WorkerModel" clone.Parent = tool -- Include AnimationId if exists local animId = clone:FindFirstChild("AnimationId") if animId and animId:IsA("StringValue") then local animCopy = animId:Clone() animCopy.Parent = tool end tool.Parent = player:WaitForChild("Backpack") end end end end3. Ensure the Hammer is Always in the First Slot
Since
StarterPackautomatically gives the hammer, it should always appear in the first slot. However, if you want to force it to stay in the first slot, you can add a small script inStarterPlayerScriptsto reorder tools:-- StarterPlayerScripts > HammerSlotManager (LocalScript) local Players = game:GetService("Players") local player = Players.LocalPlayer local backpack = player:WaitForChild("Backpack") local function reorderTools() local hammer = backpack:FindFirstChild("Hammer") if hammer then -- Move hammer to the first slot hammer.Parent = nil hammer.Parent = backpack end end backpack.ChildAdded:Connect(reorderTools) reorderTools() -- Initial check4. (Optional) Prevent the Hammer from Being Dropped
If you want to ensure players can't drop the hammer, add this to the hammer tool's script:
-- Inside the Hammer tool's LocalScript script.Parent.CanBeDropped = falseFinal Notes
- The hammer will now always be given via
StarterPackand won't interfere with your tool-saving system. - The hammer will not be saved in the player's data, preventing conflicts.
- The hammer will always appear first in the backpack.
This should fix your issue while keeping your tool-saving system intact! Let me know if you need any adjustments. 🚀
- The hammer will now always be given via
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.