How would i play an animation when the player holds down a key, and stop it when the player lets go?

The title is pretty self explanatory, so im creating a blocking script and i want it so the player will play the block animation every time the player presses and holds a key. I want the animation to stop when the player lets go. How could i achieve that simply? I have a base for a script but im not sure if it’ll work. Heres the script

Code
---------------------------------------------------------
--Variables and Instances
local player = game.Players.LocalPlayer
local UIS = game:GetService("UserInputService")
local char = player.Character or player.CharacterAdded:Wait()

local hum = char:WaitForChild("Humanoid")
local anim = script:WaitForChild("Animation")
local animTrack = hum.Animator:LoadAnimation(anim)

local Block = Instance.new("BoolValue")
local debris = game:GetService("Debris")
local bool = false
---------------------------------------------------------
--Instance Confoguration
Block.Name = "Block"
---------------------------------------------------------
--User Input
UIS.InputBegan:Connect(function(input, chat)
	if chat then return end
	
	if input.KeyCode == Enum.KeyCode.F then
		if bool == false then
			bool = true
			print("e")
			while bool == true do
				print(player.Name, "is holding down F")
				task.wait(1)
			end
			wait(5)
			bool = false
		end
	end
end)

Help is appreciated, thank you for your time

1 Like
animTrack = humanoid:LoadAnimation(anim)

UIS.InputBegan:Connect(function(input)
   if input.KeyCode == Enum.KeyCode.F then
     animTrack:Play()
   end
end)

UIS.InputEnded:Connect(function(input)
   if input.KeyCode == Enum.KeyCode.F then
     animTrack:Stop()
   end
end)
3 Likes