Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 5 years ago

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

Log in to vote
1
Answered by 5 years ago

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.

0
Thanks for the reply, the script works perfectly! SpacePuppyMan 31 — 5y
Ad

Answer this question