Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How to give a player a gear from PlayerGui?

I have the following script


local price = 10 --change the price of the item here
local item = game.ReplicatedStorage.Gears["SpeedCoil"] -- change this to the name of the gear in replicated Storage


script.Parent.MouseButton1Click:connect(function(player)
	local x = game.Players.LocalPlayer.leaderstats.Coins.Value
	local player = game.Players.LocalPlayer
	local backpack = player.Backpack
	print(x)
	x = x-price
	
	item:Clone().Parent = backpack
	
	
	
	

	
	
	
	
end)

There is a Button in StaterGui. Whenever a player clicks it this code is run. This is supposed to give the player the gear, which it does, but only that player can see it, and it doesn't work. I understand this has something to do with the gear being given from a localscript instead of a serverscript, but I don't know how to get the message that a gear needs to be added to the player to a serverscript, when a local script can't access anything else.

Is this even possible, and am I understanding this correctly? Any help would be appreciated.

1 answer

✓ Accepted answer

This is due to the way roblox servers interact with the client. The client cannot edit directly, and instead must send data to the server through server-created holes, called "Remote events".

I made a basic system, but instead of using the coin leaderstats, i just made a variable. please, if using this script, just change it for the leaderstats path instead.

https://prnt.sc/q7g4na for the areas in which different things go (server script in serverscriptservice), localscript inside button, remote event in replicated storage.

Local script

local coins = game.ReplicatedStorage.coinValue.Value

script.Parent.MouseButton1Click:Connect(function()
	if coins > 10 then
		game.ReplicatedStorage.giveGear:FireServer("Pistol", 10)
	else
		script.Parent.Text = "Cannot afford"
		wait(2)
		script.Parent.Text = "Default Buy Text"
	end
	
end)

Server script

game.ReplicatedStorage.giveGear.OnServerEvent:Connect(function(plr, gear, cost)
	print("Server event recieved")
	print(plr.Name.." - "..gear.. " - ".. cost)
	local tool = game.ServerStorage:FindFirstChild(gear)
	local char = plr.Character
	local coins = game.ReplicatedStorage.coinValue.Value -- Replace with leaderstat coins
	
	print("Current coins: "..coins)
	
	if tool then
		print("Tool found")
		if coins >= cost then
			local clone = tool:clone()
			clone.Parent = plr:FindFirstChild("Backpack")
			coins = coins - cost
			print("Current coins:"..coins)
		end
	else
		print("not a tool")
	end
end)

Hope this helps :)

This discussion is preserved as it was. New answers, comments, and votes are closed.