How could I make a shop usable?
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:
01 | local img = script.Parent.ItemImage |
02 | local cost = script.Parent.ToolCost |
03 | local name = script.Parent.ToolName |
04 | local desc = script.Parent.Description |
05 | local buy = script.Parent.Buy |
07 | local replicatedStorage = game:GetService( "ReplicatedStorage" ) |
08 | local tools = replicatedStorage:WaitForChild( "Tools" ) |
09 | local buyTool = replicatedStorage:WaitForChild( "BuyTool" ) |
11 | local mainShop = script.Parent:WaitForChild( "MainShop" ) |
12 | local template = mainShop:WaitForChild( "Template" ) |
14 | function GetChildrenAlphabetical(instance) |
15 | local children = instance:GetChildren() |
16 | table.sort(children, function (c 1 , c 2 ) |
17 | return c 1. Name:lower() < c 2. Name:lower() |
24 | local tool = GetChildrenAlphabetical(tools) |
26 | for index, tool in pairs (tool) do |
27 | if tool:IsA( "Tool" ) then |
28 | local toolElement = template:Clone() |
29 | toolElement.Parent = mainShop |
30 | toolElement.Name = tool.Name |
31 | if tool.TextureId ~ = "" then |
32 | toolElement.Image = tool.TextureId |
34 | toolElement.Visible = true |
42 | toolElement.MouseButton 1 Click:Connect( function () |
43 | img.Image = toolElement.Image |
44 | name.Text = tool.name.Value |
45 | desc.Text = tool.Desc.Value |
46 | if tool.Cost.Value = = 0 then |
49 | cost.Text = "$" .. tool.Cost.Value |
57 | buy.MouseButton 1 Click:Connect( function () |
58 | local buyTool = replicatedStorage:WaitForChild( "BuyTool" ) |
59 | local result = buyTool:InvokeServer(tool, tool.Cost) |
GiveItem Script:
01 | game.ReplicatedStorage.BuyTool.OnServerInvoke = function (player, item, cost) |
02 | if game.ReplicatedStorage.Tools:FindFirstChild(item.Name) and item:FindFirstChild( "Cost" ) then |
03 | if player.leaderstats.blinds.Value > = item.Cost.Value then |
04 | local tool = game.ReplicatedStorage.Tools [ item.Name ] :Clone() |
05 | player.Backpack:ClearAllChildren() |
06 | player.StarterGear:ClearAllChildren() |
07 | tool.Parent = player.Backpack |
09 | local starterTool = tool:Clone() |
10 | starterTool.Parent = player.StarterGear |
12 | player.leaderstats.blinds.Value = player.leaderstats.blinds.Value - cost.Value |
16 | return "NotEnoughCash" |
19 | return "NoItemOrNoCostValue" |
If someone could give me an answer, that would be great. Thanks!