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

How would I go about fixing my key input animation script?

So, I researched about this script that allows a character to press a key (F in this case) and a animation would be played. I tried to use the script but it wouldnt work. How would I go about fixing it?


local player = game:GetService("Players").LocalPlayer
local character = player.Character or player.Character:Added()
local humanoid = character:WaitForChild("Humanoid")
local anim = Instance.new("Animation")
anim.AnimationId = "rbxassetid://511512134"
function playAnimation(Anim)
    local track = humanoid:LoadAnimation(Anim)
    track:Play()
end
game:GetService("UserInputService").InputBegan:connect(function(input ,proc)
    if not proc then
        if input.KeyCode == Enum.KeyCode.F then
            playAnimation(anim)
        end
    end
end)

2 comments

0

You capitalized the 'A' in "anim" when you loaded the animation inside of the function. That's one of your errors I just found.

0

That is not the problem here as he passes the animation on line 13, though he does not need to do this.

1 answer

✓ Accepted answer

The problem is the way you are waiting for the character:-

local character = player.Character or player.Character:Added()

Added is not an event for a model, also we need to be using the player object: like so:-

local character = player.Character or player.CharacterAdded:wait()

We use the CharacterAdded and then the wait RBXScriptSignal. This will wait till the event is fired meaning we will have access to the character.

For this kind of task it would be best to use StarterCharacterScripts as we only need access to the players humanoid:-

-- This script will be in the players model 
local humanoid = script.Parent:WaitForChild("Humanoid")
local anim = Instance.new("Animation")
anim.AnimationId = "rbxassetid://511512134"

-- you should re-think this part as you do not need to pass the variable nor load the animation each time you press the key
local function playAnimation(Anim)
    local track = humanoid:LoadAnimation(Anim)
    track:Play()
end

game:GetService("UserInputService").InputBegan:connect(function(input ,proc)
	if input.KeyCode == Enum.KeyCode.F then
		print('ran2')
		playAnimation(anim)
	end
end)

It would also be best I you did not load the animation every time the player presses the f key, instead load it once then play the animation track when the key is pressed.

I hope this helps, please comment if you do not understand how / why this script works.

1 comment

0

How do I make the animation loop as long as I press the button

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