C To Crouch Script Animation Issue

Hello!
I am making a crouching script so if you click c you crouch, and I have an animation for it. But whenever I click c, it plays the animation even if i don’t move. Also, it only plays the animation for a second. I want it to play the animation when I move until I click c again. Thanks for any help.
Here is the script. (It is a local script in StarterCharacterScripts)

local UserInputService = game:GetService("UserInputService")
local Character = script.Parent
local Humanoid = Character:WaitForChild("Humanoid")
local isCrouching = false
local Animation = Humanoid:LoadAnimation(script:WaitForChild("Animation"))

UserInputService.InputBegan:Connect(function(key)
	if key.KeyCode == Enum.KeyCode.C then
		if not isCrouching then
			isCrouching = true
			Animation:Play()
			Humanoid.WalkSpeed = 10
		else
			Animation:Stop()
			Humanoid.WalkSpeed = 16
			isCrouching = false
		end
	end 
end)

Sorry it was hard to understand your issue but from what I can tell uhh

when you press C, you want the crouching animation to play, even when you’re not moving and moving, but when you press C again, it’ll end the animation…

Under local Animation = Humanoid:LoadAnimation(script:WaitForChild(“Animation”))
try do Animation.Looped = true

Let’s break this down.

You say the animation only plays for a second? Is the animation looped and is the priority set to action?

Your code should look like this

local UserInputService = game:GetService("UserInputService")
local Character = script.Parent
local Humanoid = Character:WaitForChild("Humanoid")
local isCrouching = false
local Animation = Humanoid:LoadAnimation(script:WaitForChild("Animation"))

UserInputService.InputBegan:Connect(function(key, gpe)
 if gpe then return end -- this is just so if they are typing then it doesnt work basically
	if key.KeyCode == Enum.KeyCode.C then
		if isCrouching ~= true then
			isCrouching = true
			Animation:Play()
			Humanoid.WalkSpeed = 10 
                      print("played")
               else
                       print("stopped")
                      	Animation:Stop()
			Humanoid.WalkSpeed = 16
			isCrouching = false
              end
	end 
end)

Not much of a difference but the next step will be to do print checks.

Thanks for the help, I didn’t think it would be solved so fast! What you did now make sense.

1 Like
local UserInput = game:GetService("UserInputService")
local Character = script.Parent
local Humanoid = Character:WaitForChild("Humanoid")
local Animation = script:WaitForChild("Animation")
local Track = Humanoid:LoadAnimation(Animation)
Track.Priority = Enum.AnimationPriority.Action
Track.Looped = true

local Crouching = false

UserInput.InputBegan:Connect(function(Key, Processed)
	if Processed then return end
	
	if Key.KeyCode == Enum.KeyCode.C then
		Crouching = not Crouching
		if Crouching then
			Track:Play()
			Humanoid.WalkSpeed = 10
		elseif not Crouching then
			Track:Stop()
			Humanoid.WalkSpeed = 16
		end
	end 
end)