Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Sword keeps breaking after purchase from GUI?

Asked by 5 years ago

I'm trying to make a game where you can buy a sword w/ the starting cash from some leaderstats. If I put the sword into Starterpack, it works fine. However, once I purchase the sword and it goes into my inventory, it seems to just break the scripts. Here is my current script:

script.Parent.MouseButton1Click:Connect(function()

local PriceOfItem = game.ReplicatedStorage.Buyables.Sword.Price.Value

if game.Players.LocalPlayer.leaderstats.Cash.Value >= PriceOfItem then

local clone = game.ReplicatedStorage.Buyables.Sword:Clone()

clone.Parent = game.Players.LocalPlayer.Backpack

game.Players.LocalPlayer.leaderstats.Cash.Value = game.Players.LocalPlayer.leaderstats.Cash.Value - 50

end

end)

P.S. This is in a LocalScript in a textbutton in a Gui. If you're wondering about the "Buyables" section, it's a folder in ReplicatedStorage.

0
Just realized I didn't put the whole thing in a code block. Extremely apologetic, can I edit the post? Instincr 16 — 5y
0
How is a local script going to get to the server? ABK2017 406 — 5y
0
That wouldn't work with FE theking48989987 2147 — 5y

1 answer

Log in to vote
0
Answered by
CjayPlyz 643 Moderation Voter
5 years ago
Edited 5 years ago
local Player = game:GetService("Players").LocalPlayer
local Cash = Player:WaitForChild("leaderstats"):WaitForChild("Cash")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RemoteEvent = ReplicatedStorage:WaitForChild("RemoteEvent")
local Sword = ReplicatedStorage:WaitForChild("Buyables"):WaitForChild("Sword")
local Price = Sword:WaitForChild("Price")

local function MouseButton1Click ()
    if Cash.Value >= Price then
        local NewSword = Sword:Clone()
        NewSword.Parent = Player.Backpack
        RemoteEvent:FireServer(Price)
    end
end

script.Parent.MouseButton1Click:Connect(MouseButton1Click)

Insert a remoteevent in the replicatedstorage then a script in the serverscriptservice then write this in that script.

local ReplicatedStorage = game:GetService("ReplicatedStorage"):WaitForChild("RemoteEvent")

local function OnServerEvent (Player, Price)
    local Cash = Player.leaderstats.Cash
    Cash.Value = Cash.Value - Price
end

ReplicatedStorage.OnClientEvent:Connect(OnServerEvent)

The reason why you should use remote event is because when you change a value in a local script it wont replicate to the server or all the clients, it means that if you change the value of money using a local script to.. example from 120 to 70 the client will see the that the value changed but in the other clients they will still see you have 120 money.

Ad

Answer this question