Tool not going into players backpack

I was trying to make it so that when you click on a cake, it gives you a cake to eat. When I try to click on the cake it gives me this error in the output bar: Workspace.ChocolateCake.GiveCake:6: attempt to index nil with ‘Backpack’ - Server - GiveCake:6
Here is my code:
local ClickDetecter = script.Parent.ClickDetector
local CakeTool = game.ReplicatedStorage.Food["Chocolate cake"]:Clone()
local player = game.Players.LocalPlayer

ClickDetecter.MouseClick:Connect(function()
CakeTool.Parent = player.Backpack
end)

If this is in a server script:

local ClickDetecter = script.Parent.ClickDetector

ClickDetecter.MouseClick:Connect(function(player) -- MouseClick passes the player who clicked
   local CakeTool = game.ReplicatedStorage.Food["Chocolate cake"]:Clone()
   CakeTool.Parent = player.Backpack
end)

You cannot define the Local Player in a Server Script

however you can use the ClickDetector's MouseClick parameter which is the Player object as shown in the above post

Add it in LUA boxs so we see it maybe a bit clear?

local ClickDetecter = script.Parent.ClickDetector
local CakeTool = game.ReplicatedStorage.Food["Chocolate cake"]:Clone()
local player = game.Players.LocalPlayer

ClickDetecter.MouseClick:Connect(function()
CakeTool.Parent = player.Backpack
end)

And, you define localPlayer in a script. Here is the fix:

local ClickDetector = script.Parent.ClickDetector
local CakeTool = game.ReplicastedStorage.Food["Chocolate cake"]
local player = game.Players

ClickDetector.MouseClick:Connect(function()
local CakeToolClone = CakeTool:Clone()
CakeToolClone.Parent = player.Backpack
end

You can’t define local player in a script, because it’s the server, there isn’t a local player.

That would be referencing the Players service, not an actual player, so this code would error.

That wouldn’t work even if it was a local script since you’re defining the playerService.

make sure that your code is in a local script; you can’t get the local player from a normal script

If your code is a server script:

local ClickDetecter = script.Parent.ClickDetector
local CakeTool = game.ReplicatedStorage.Food["Chocolate cake"]

ClickDetecter.MouseClick:Connect(function(plr)
local tool = CakeTool:Clone()
tool.Parent = plr.Backpack
end)
1 Like