So I have been making a shop for my game, and when you press the buy button, it gives you the item, but when you press the button on a different item, it doesn't give you the item, but still charges you for the item. I think it's that the game saves the variable and when you buy a different item, it gives you the first one. Also, this game's inventory is only supposed to have one item at a time, so the item gets replaced instead of added to the inventory. Here's the code:
BuyButton Script:
local img = script.Parent.ItemImage local cost = script.Parent.ToolCost local name = script.Parent.ToolName local desc = script.Parent.Description local buy = script.Parent.Buy local replicatedStorage = game:GetService("ReplicatedStorage") local tools = replicatedStorage:WaitForChild("Tools") local buyTool = replicatedStorage:WaitForChild("BuyTool") local mainShop = script.Parent:WaitForChild("MainShop") local template = mainShop:WaitForChild("Template") function GetChildrenAlphabetical(instance) local children = instance:GetChildren() table.sort(children, function(c1, c2) return c1.Name:lower() < c2.Name:lower() end) return children end -- local tool = GetChildrenAlphabetical(tools) for index, tool in pairs(tool) do if tool:IsA("Tool") then local toolElement = template:Clone() toolElement.Parent = mainShop toolElement.Name = tool.Name if tool.TextureId ~= "" then toolElement.Image = tool.TextureId end toolElement.Visible = true img.Visible = false cost.Visible = false name.Visible = false desc.Visible = false buy.Visible = false toolElement.MouseButton1Click:Connect(function() img.Image = toolElement.Image name.Text = tool.name.Value desc.Text = tool.Desc.Value if tool.Cost.Value == 0 then cost.Text = "Free" else cost.Text = "$" .. tool.Cost.Value end img.Visible = true cost.Visible = true name.Visible = true desc.Visible = true buy.Visible = true buy.MouseButton1Click:Connect(function() local buyTool = replicatedStorage:WaitForChild("BuyTool") local result = buyTool:InvokeServer(tool, tool.Cost) print(result) end) end) end end
GiveItem Script:
game.ReplicatedStorage.BuyTool.OnServerInvoke = function(player, item, cost) if game.ReplicatedStorage.Tools:FindFirstChild(item.Name) and item:FindFirstChild("Cost") then if player.leaderstats.blinds.Value >= item.Cost.Value then local tool = game.ReplicatedStorage.Tools[item.Name]:Clone() player.Backpack:ClearAllChildren() player.StarterGear:ClearAllChildren() tool.Parent = player.Backpack local starterTool = tool:Clone() starterTool.Parent = player.StarterGear player.leaderstats.blinds.Value = player.leaderstats.blinds.Value - cost.Value return "BoughtItem" else return "NotEnoughCash" end else return "NoItemOrNoCostValue" end end
If someone could give me an answer, that would be great. Thanks!