Players.GEILER123456.Backpack.Tool.Script:16: attempt to index nil with 'Button2Down'

What is wrong with my Item-Give script?
Output: [Players.GEILER123456.Backpack.Tool.Script:16: attempt to index nil with ‘Button2Down’

for _, player in pairs(game.Players:GetChildren()) do
	local RS = game:GetService("ReplicatedStorage")
	local Tool = script.Parent
	local Handle = Tool.Handle
	local mouse = player:GetMouse()
	local isEquipped = false
	
	Tool.Equipped:Connect(function()
		isEquipped = true
	end)
	
	Tool.Unequipped:Connect(function()
		isEquipped = false
	end)
	
		mouse.Button2Down:Connect(function()
			if isEquipped == true then --If the item is equipped
				print("Yes1") 
				local MouseTarget = mouse.Target  --Thing that gets targetted
				local MouseTargetCharacter = mouse.Target.Parent  
				local TargetHumanoid = MouseTargetCharacter:FindFirstChild("Humanoid")
				
				if TargetHumanoid then
					print("Yes2") 
					local TargetPlayer = game.Players:GetPlayerFromCharacter(MouseTargetCharacter)
					local TargetPlayerBackpack = TargetPlayer:FindFirstChild("Backpack")
					local MyBackpack = player:FindFirstChild("Backpack")
					local ToolToClone = RS:FindFirstChild("Tool")
					
					local ToolClone = ToolToClone:Clone()
					print("Yes3") 
					ToolClone.Parent = TargetPlayerBackpack --Tool gets added to the target's inventory
					print("Yes4")   
					
					MyBackpack.Tool:Destroy()
					print("Yes5")  							 --My tool gets destroyed bc I gave it to him

				end
			end
		end)

end

It doesn’t print anything, only the error.

I’m certain that you can only get the player’s mouse via LocalScript. Correct me if I’m wrong.

1 Like

You are right, you can only access the mouse from the local script.

1 Like

Maybe instead of the for i,v in pairs loop I should do a playerAdded event?

You must get the player’s mouse with a LocalScript. If you have to make use of the mouse for the server, use RemoteEvents.

1 Like

Try printing mouse, from the error, it looks like mouse is null. I’m sure it only works on client scripts (LocalScript), not server script.

Yes but LocalScript runs from the player so there’s no need. You could do game.Players.LocalPlayer instead.

Please “if (isEquipped) then”, “isEqupped == true” is redundant
Please “Players:GetPlayers()” instead of “Players:GetChildren()”

1 Like