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

How to make an event only happen when a player is holding an item?

Hi, I'm currently working on a simple survival type game and I'm trying to make a script that lets a player eat a piece of food if they press a key while there holding the item. Here is my script:

game.Players.LocalPlayer.Backpack.Weat.Equipped:Connect(function()
	local player = game.Players.LocalPlayer
local mouse = player:GetMouse()
mouse.KeyDown:connect(function(key)
    if key == "e" then
        print("Food Eaten")
   end
end)
end)

Thanks

1 answer

✓ Accepted answer

I believe KeyDown is deprecated, therefore, on my answer I used the User Input Service. This script needs to be in the starter player scripts and also needs to be in a local script.

game.Players.LocalPlayer:WaitForChild("Backpack").Weat.Activated:Connect(function()
	    local player = game.Players.LocalPlayer
	local mouse = player:GetMouse()
	
	print("Tool was equipped!")
	
	function OnKeyPressed(Input)
	
		if Input.KeyCode == Enum.KeyCode.E then
			
			print("Food Eaten")
			
		end
		
	end
	game:GetService("UserInputService").InputBegan:Connect(OnKeyPressed)
	
end)

I hope this works for you.

1 comment

0

Thanks for the reply, the script works perfectly!

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