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

How can I clone a tool to StarterGear via LocalScript?

Asked by 4 years ago

This is the code I created for a shop GUI that I'm working on but I can't get the tools to clone to StarterGear because this code is in a Local script.

player = script.Parent.Parent.Parent.Parent.Parent
money = player.leaderstats.Credits
price = script.Parent.Price.Value
tool = game.ReplicatedStorage:findFirstChild("TG45")


function buy()
--if player.Backpack:FindFirstChild(tool) == nil then   
if money.Value >= price then
local a = tool:clone()
a.Parent = player.Backpack
a.Parent = player.StarterGear

end
end
script.Parent.MouseButton1Down:connect(buy)
0
you will have to use remotes if your game is FE 0msh 333 — 4y

1 answer

Log in to vote
1
Answered by
royaltoe 5144 Moderation Voter Community Moderator
4 years ago

You can have a remote event that gives a player the tool:

Create a RemoteEvent in your ReplicatedStorage and name it GiveItem

In a local script, fire that remote event with the name of the tool you want to give the player

giveItem = game.ReplicatedStorage.GiveItem
giveItem:FireServer("TG45")

We can catch that remote event on the server. The following code below runs giveItem.OnServerEvent:Connect(function(player, itemBeingGiven) when the player fires the remote event from a localscript using the code I posted above.

We check if the item that the player is trying to get exists and if the player is allowed to have that tool using the playerCanHaveTool function. playerCanHaveTool can check for anything.

A player can fire the remote event and give themselves any tool we want, but this function stops them from actually receiving the tool if they're not allowed. An example of this is if the player tries to buy a tool and they don't have enough money, this function will stop them from getting that item. Let me know if you have any questions.

giveItem = game.ReplicatedStorage.GiveItem
rs = game:GetService("ReplicatedStorage")


--check if the player can have the tool i.e. they have enough money to buy the tool
function playerCanHaveTool()
    if (they can have the tool)then
        return true
    else
        return false
    end
end

--this runs when we fire our 'give item' remote event
giveItem.OnServerEvent:Connect(function(player, itemBeingGiven)
    local tool = rs:FindFirstChild(itemBeingGiven)

    --only give the player the tool if the tool exists and playerCanHaveTool() returns true
    if(tool and playerCanHaveTool())then
        --put the tool in the player's backpack
        local clone = tool:Clone()
        clone.Parent = player.Backpack
    end
end)
Ad

Answer this question