Error when giving tools to a player

Hiya, I’m trying to make it so at the click of a GUI, the player get’s given a tool that’s located in ServerStorage. I’ve looked at other topics on things similar however nothing has helped me and I keep getting the same error.


Script:

 script.Parent.MouseButton1Click:Connect(function()
    local backpack = player:WaitForChild("Backpack")
    local cloneValue = game.ServerStorage.Value:Clone()
    cloneValue.Parent = backpack
 end

Any help would be appreciated.
Thanks for your time.

1 Like

Whats the error message?

And are you trying to equip as well, or just put in the backpack?

Just putting in the backpack is fine.
The error message is attempt to index nil with 'WaitForChild

try

	local backpack = player:WaitForChild("Backpack")
	local cloneTool = game.ServerStorage.TestTool:Clone()
	cloneTool.Parent = backpack

Your mistake is that you’re calling the function from a LocalScript inside the player but players can’t access the ServerStorage. So you basically must put the tool into ReplicatedStorage or you do this with RemoteFunctions and a Script inside ServerScriptService because a ServerScript inside ServerScriptService can access the ServerStorage.

The script is located in a part in the Workspace. Would that make a difference?

Scripts inside workspace can’t access ServerStorage only Scripts inside ServerScriptService so far I know.

It should work if the GUI is an SurfaceGui, the problem was that you didn’t put the player when you called the function.

script.Parent.MouseButton1Click:Connect(function(player)
local backpack = player:WaitForChild(“Backpack”)
local cloneValue = game.ServerStorage.Value:Clone()
cloneValue.Parent = backpack
end)

I believe you have to get the tool from an area other than the Server Storage. Instead, try putting the tool inside the replicated storage or lighting. But that’s not all, you also have to look into remote events since Gui buttons only work on the client-side.

The script is located in a part in the Workspace. Would that make a difference?

Make sure the script stays with the player to keep from any random errors happening. Also, make sure to have the script as a Local script, otherwise the button won’t work.

Can you send the entire script or at least the line at which the error is occuring?

The error was occuring here.
30 chars

What’s the line where you define ‘player’?

It’s the second line of the script.
A simple player = game.Players.LocalPlayer

If you’re using a server sided script, LocalPlayer won’t work.

That’s true, try to keep it with the player, for example, the StarterGui.

What you can do is insert a click detector into the object and obtain the player who clicked it.