Connect the C for Crouch key with Text Button so it works with key and button

Hey everyone rn in my game I want to be able to crouch on both pc and on Ipad etc. and I currently don’t exactly know how to convert like not convert but uh make it able for both the script is inside the textbutton

local TextButton = "CrouchButton"
local keybind = "C"
local animationId = "17667816899"  

--// Variables
local UserInputService = game:GetService("UserInputService")

local player = game:GetService("Players").LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local humanoid = character:WaitForChild("Humanoid")

local animation = Instance.new("Animation")
animation.AnimationId = 'rbxassetid://' .. animationId

local animationTrack = humanoid:WaitForChild("Animator"):LoadAnimation(animation)
animationTrack.Priority = Enum.AnimationPriority.Action

local crouching = false


--// Functions
UserInputService.InputBegan:Connect(function(input, gameProcessedEvent)
	if gameProcessedEvent then return end

	if input.KeyCode == Enum.KeyCode[keybind] then
		if crouching then
			humanoid.WalkSpeed = 16
			crouching = false
			animationTrack:Stop()
			character.HumanoidRootPart.CanCollide =  true
		else
			humanoid.WalkSpeed = 8
			crouching = true
			animationTrack:Play()
			character.HumanoidRootPart.CanCollide =  false
		end
	end

	while wait() do


		if humanoid.MoveDirection.Magnitude > 0 then


			animationTrack:AdjustSpeed(1) 


		else


			animationTrack:AdjustSpeed(0)


		end
	end

end)
1 Like

Separate your UserInputService.InputBegan function (erase :Connect and everything before it, as well as the parentheses surrounding the whole function) and replace it with a named function.

Then, do UserInputService.InputBegan:Connect(yourFunctionName).
To connect the text button, I recommend the following:

TextButton.Activated:Connect(function()
  yourFunctionName( [pass any necessary InputObjects])
end)

The reason I recommend this as opposed to a :Connect(yourFunctionName) is due to better support with ContextActionService, which I highly recommend you switch to instead as unbinding these inputs becomes much easier. Though, for your purposes if you don’t want to change up the script too greatly, UserInputService is still a good method.

For future reference, if you want to keep your scripts modular and easy to modify in the future, try to stray from anonymous functions. It can help a lot when expanding to new platforms. (Of course, this is context-specific too, you don’t need to use exclusively global functions.)

1 Like

thx bro it worked!!!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.