Script doesn't work when if statement is added

So im making a crouching script and it works but i added a if statement so you can crouch then stand

Code With if statement:

local players = game:GetService("Players")

local player = players.LocalPlayer

local UIS = game:GetService('UserInputService')
repeat wait() until player.Character
local Character = player.Character
local crouch = player.Character.Humanoid:LoadAnimation(script.CrouchIdle)
local crouchwalk = player.Character.Humanoid:LoadAnimation(script.CrouchWalk)

local crouching = false
UIS.InputBegan:connect(function(key, gameProcessed)
	if key.KeyCode == Enum.KeyCode.C and gameProcessed == false then
		if crouching == false then
			crouch:Play()
		crouching = true

			end
		if crouching == true then
			crouch:Stop()
			crouching = false
		end
	end
end)

Character.Humanoid.Running:Connect(function(speed)
	if speed >0 and crouching == true then
		crouchwalk:Play()
	end
	if speed <1 then
		crouchwalk:Stop()
	end
	end)

Result: https://gyazo.com/0c51636a10a9afdd89097879aa0daee0

Code without if statement:

local players = game:GetService("Players")

local player = players.LocalPlayer

local UIS = game:GetService('UserInputService')
repeat wait() until player.Character
local Character = player.Character
local crouch = player.Character.Humanoid:LoadAnimation(script.CrouchIdle)
local crouchwalk = player.Character.Humanoid:LoadAnimation(script.CrouchWalk)

local crouching = false
UIS.InputBegan:connect(function(key, gameProcessed)
	if key.KeyCode == Enum.KeyCode.C and gameProcessed == false then
			crouch:Play()
crouching = true
	end
end)

Character.Humanoid.Running:Connect(function(speed)
	if speed >0 and crouching == true then
		crouchwalk:Play()
	end
	if speed <1 then
		crouchwalk:Stop()
	end
	end)

Result: https://gyazo.com/ffdd9bdbbf8b89a3663fbf33fa85489b

my desired result is for the player to be able to crouch and stand back up

help pls :slightly_smiling_face:

Maybe make it if the player has held the key they’ll crouch.

local UIS = game:GetService('UserInputService')
repeat wait() until player.Character
local Character = player.Character
local crouch = player.Character.Humanoid:LoadAnimation(script.CrouchIdle)
local crouchwalk = player.Character.Humanoid:LoadAnimation(script.CrouchWalk)

local crouching = false
UIS.InputBegan:connect(function(key, gameProcessed)
	if key.KeyCode == Enum.KeyCode.C and gameProcessed == false then
			crouch:Play()
crouching = true
	end
end)

UIS.InputEnded:Connect(function(input)
if input.KeyCode == Enum.KeyCode.C then
crouch:Stop()
crouching = false
end
end)
1 Like