How do you think of my Crouch Animation code?

I want to improve the code by adding an module script, what do you agree and dislike about this newly written code?


-- // Variables // --
local UserInputService = game:GetService('UserInputService')
local Players = game:GetService('Players')
local Player = Players.LocalPlayer
local Key = 'C'

-- // Crouch Animation // --
local AnimationBegan = Instance.new('Animation')

-- // Functions // --
local function InsertId(Object, Id)
	if (Object:IsA('Animation')) then
         Object.AnimationId = 'rbxassetid://' .. Id
	end
end
InsertId(AnimationBegan, 04846138403)

-- // Main Script & Execution // --

UserInputService.InputBegan:Connect(function(inputGiven)
	
	if inputGiven.KeyCode == Enum.KeyCode[Key] then
		local LoadAnimation = Player.Character.Humanoid:LoadAnimation(AnimationBegan)
		LoadAnimation:Play()
	end
	
end)


4 Likes

This is just me personally, but I would make it so that instead of

local Key = 'C'

I would do the full Enum there

local Key = Enum.KeyCode.C

Then you can just have

if inputGiven.KeyCode == Key then

Again, I think this is just me personally.

1 Like

:+1:

Looks good.

30 characters

For the event InputBegan, there is an argument named “gameProcessedEvent”, checking this to make sure it is false before executing the keybind this means the crouch will not fire if the player is typing in chat, also when they are typing in boxes and other game-related input. For more detail you can check the wiki article, just make sure you are referring to the UserInputService section.

This bit of code is SUPER redundant. First off, you already assume you are using animation, so there is no need to check with IsA.

In addition, you can simply do:

AnimationBegan.AnimationId = 'rbxassetid://04846138403'

Don’t over complicate your code, as it can make it hard to read and it can take up un-needed space, which in the end lags your game (to an extent).

This is a bit weird, I would recommend ContextActionService for the following reasons:

  • You can bind and unbind keys and buttons at any time.
  • Automatically combines support across all platforms, and auto makes mobile buttons.

Hope I helped both you and anybody scrolling by :slight_smile: