Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How do I make a keybinding animation script?

So I have this keybind animation script. When I tested it out it wont work. What did I do wrong? Also I want the animation to play when key is pressed and stop when the key is unpressed. So, when you press and hold the key the animation will play and when you lift you finger from the key the animation will stop.

repeat wait() until game.Players.LocalPlayer.Character~=nil
local plr=game.Players.LocalPlayer
local chr=plr.Character
local hum=chr:WaitForChild("Humanoid")
local UserInput=game:GetService("UserInputService")


local crtAnimation


local normalSpeed=16
--put the keycode for each animation followed by the animation (animation must be inside the local script as well
local animationsList={
	[Enum.KeyCode.LeftShift] = {hum:LoadAnimation(script:WaitForChild("Ready")),16},  -- the 16 and the 1 below are the speed of the player
	[Enum.KeyCode.Q] = {hum:LoadAnimation(script:WaitForChild("Sit")),16}, 
}
local function StopAllAnims()
	for _,v in pairs(animationsList) do
		if crtAnimation~=v[1] and v[1].IsPlaying then v[1]:Stop() end
	end
end
UserInput.InputBegan:connect(function(input) 
	if animationsList[input.KeyCode] ~= nil and UserInput:GetFocusedTextBox()==nil then
		if animationsList[input.KeyCode][1] ~= crtAnimation then
			crtAnimation=animationsList[input.KeyCode][1]
			hum.WalkSpeed=animationsList[input.KeyCode][2]
				StopAllAnims()
			crtAnimation:Play()
		else
			hum.WalkSpeed=normalSpeed
			crtAnimation=nil
			StopAllAnims()
		end
	end
end)

1 answer

Why not just elseif statements? Like so:

local plr = game.Players.LocalPlayer
local UIS = game:GetService("UserInputService")

UIS.InputBegan:connect(function(key, GPE) -- GPE is chat :)
	if key.KeyCode == Enum.KeyCode.T and not GPE then
		local anim = plr.Character.Humanoid:LoadAnimation(game.ReplicatedStorage.Animation1)
		anim:Play()
		wait(10)
		anim:Stop()
	elseif key.KeyCode == Enum.KeyCode.S and not GPE then
		local anim = plr.Character.Humanoid:LoadAnimation(game.ReplicatedStorage.Animation1)
		anim:Play()
		wait(10)	
		anim:Stop()
	elseif key.KeyCode == Enum.KeyCode.A and not GPE then
		local anim = plr.Character.Humanoid:LoadAnimation(game.ReplicatedStorage.Animation1)
		anim:Play()
		wait(10)	
		anim:Stop()
	end
end()

So on so forth. Sorry for the extensive amount of code, I just wanted to give a good representation of what I mean. Hopefully this helped, and I am pretty sure it is a lot cleaner and a lot more efficient then your previous code.

This discussion is preserved as it was. New answers, comments, and votes are closed.