How do i make a tool register in the player's backpack

i would like to find some errors in my code and hope to achieve what i need in the title.

local part = Instance.new("Part")
local tool = Instance.new("Tool")
local clickDetector = Instance.new("ClickDetector")

clickDetector.Parent = part

local function onClick()
   part.Parent = tool
   tool.Parent = game.Players.LocalPlayer.Backpack
end

part.clickDetector.MouseClick:Connect(onClick)

one problem i face is that it doesnt register the Local Player, and returns an error with a nil index. i dont know how to fix that, neither i know whether my code is actually correct. can someone help me out?

you cant call LocalPlayer directly using game.players.localplayer from server, use the function

---//Parts
local PartToClick = script.Parent

-- //Tool
local Tool = Instance.new("Tool", PartToClick)
local HandlePart = Instance.new("Part", Tool)
local ClickDetector = Instance.new("ClickDetector", PartToClick)


function onMouseClick(player: Player)
	
	-- //Backpack
	local Backpack = player.Backpack

	-- //Parent
	if Tool.Parent == PartToClick then
		Tool.Parent = Backpack
	else
		warn("Tool Parent:", Tool.Parent)
	end
	
end

ClickDetector.MouseClick:Connect(onMouseClick)

so in summary of your scripts:

  • first script is server script in players, and
  • second script is in server script service
    if thats what youre saying

the first script - thats js a showcase on how to get local player – ill remove that,

the second script goes into the part you are clicking OR can go into server script service.

just get part from

local part = workspace:WaitForChild("PartToClick")
2 Likes

it works, thanks a lot for the help!

1 Like