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

why isnt my animation script working? The animation is really glitchy

I want to make an animation play when i press 1 and when i press 1 again it stops, why doesnt this work?

local pl = game.Players.LocalPlayer
repeat
	wait()
until pl.Character
local char = pl.Character
local hum = char:WaitForChild("Humanoid")

local hold = false

local uis = game:GetService("UserInputService")
uis.InputBegan:Connect(function(input)
	if input.KeyCode == Enum.KeyCode.One then
		print("one")
		local sit = workspace.sit
		local track = hum:LoadAnimation(sit)
		track:Play()
	end
end)
local uis = game:GetService("UserInputService")
uis.InputBegan:Connect(function(input)
	if input.KeyCode == Enum.KeyCode.One then
		print("one")
		local sit = workspace.sit
		local track = hum:LoadAnimation(sit)
		track:Stop()
	end
end)

local script in starter player

2 answers

✓ Accepted answer

This is because you have both of your Input keys set to One so they will both activate. Try adding in some checks like this:

local pl = game.Players.LocalPlayer
repeat
    wait()
until pl.Character
local char = pl.Character
local hum = char:WaitForChild("Humanoid")
local sit = workspace.sit
local track = hum:LoadAnimation(sit) -- lets go ahead and load the animation before hand

local hold = false
local playing = false -- this is how we will determine if the animation is playing

local uis = game:GetService("UserInputService")
uis.InputBegan:Connect(function(input)
    if input.KeyCode == Enum.KeyCode.One and not playing then -- make sure it not already playing
        print("one")
		playing = true -- set it to true so we know its playing
        track:Play()
    end
end)
local uis = game:GetService("UserInputService")
uis.InputBegan:Connect(function(input)
    if input.KeyCode == Enum.KeyCode.One and playing then -- checks to see if playing is true
        print("one")
        track:Stop()
		playing = false -- set it back to false so we know its no longer playing
    end
end)

Issues

  1. You are binding two functions to the same event. Consider using one.
  2. You are stopping and playing different AnimationTracks. LoadAnimation() will return a new track
local pl = game.Players.LocalPlayer
repeat
    wait()
until pl.Character
local char = pl.Character
local hum = char:WaitForChild("Humanoid")

local hold = false

local uis = game:GetService("UserInputService")

local currentTrack
uis.InputBegan:Connect(function(input)
    if input.KeyCode == Enum.KeyCode.One then
		if currentTrack then
			currentTrack:Stop()
		else
			local sit = workspace.sit
	        currentTrack = hum:LoadAnimation(sit)
        	currentTrack:Play()

			currentTrack.Stopped:Connect(function()
				currentTrack = currentTrack:Destroy()
			end)
		end
    end
end)

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