Animation stays playing after :Stop() was called

So, my aiming animation for the gun keeps playing after I release RightMouse, specifically if I have fired while aiming. This is the code. The script is in a LocalScript placed inside of a Tool and anim2 (aiming animation) is not looped.

UIS.InputBegan:Connect(function(input, gameprocessed)
	track2 = nil
		if input.UserInputType == Enum.UserInputType.MouseButton2 then
			track2 = script.Parent.Parent.Humanoid.Animator:LoadAnimation(anim2)
			track2:Stop()
		track2:Play()
		workspace.CurrentCamera.FieldOfView = 45
	end
	UIS.InputEnded:Connect(function(input, gameprocessed)
		if input.UserInputType == Enum.UserInputType.MouseButton2 and track2 then
			track2:Stop()
			workspace.CurrentCamera.FieldOfView = 70



		end
	end)
end)

A video if anyone needs a visual.

I tried to cleanup a few things, try and see if this works.

local track2

UIS.InputBegan:Connect(function(input, gameprocessed)
    if input.UserInputType == Enum.UserInputType.MouseButton2 then
        track2 = script.Parent.Parent.Humanoid.Animator:LoadAnimation(anim2)
        track2:Stop()
        track2:Play()
        workspace.CurrentCamera.FieldOfView = 45
    end
end)

UIS.InputEnded:Connect(function(input, gameprocessed)
    if input.UserInputType == Enum.UserInputType.MouseButton2 and track2 then
        track2:Stop()
        workspace.CurrentCamera.FieldOfView = 70
    end
end)

2 Likes

You shouldn’t put a connection inside another connection without disconnecting it. Otherwise, each time the connection fires, a new connection is created and never removed.

Here is some fixed up code:

UIS.InputBegan:Connect(function(input, gameprocessed)
	-- If the correct button
	if input.UserInputType == Enum.UserInputType.MouseButton2 then
		-- Start the animation
		local track2 = script.Parent.Parent.Humanoid.Animator:LoadAnimation(anim2)
		track2:Play()
		workspace.CurrentCamera.FieldOfView = 45

		-- End the animation when the button is released
		local connection
		connection = UIS.InputEnded:Connect(function(input, gameprocessed)
			if input.UserInputType == Enum.UserInputType.MouseButton2 then
				connection:Disconnect()  -- Remove the connection
				track2:Stop()  -- Stop the animation
				workspace.CurrentCamera.FieldOfView = 70  -- Reset the FoV
			end
		end)
	end
end)
1 Like

Thank you for the tip; both of the solutions worked.

2 Likes

Both are great solutions but your main problem/error was setting track2 to nil every time a button was pressed with InputBegan.

Also it’s a good thing you showed your code, as this code would cause issues with memory leak, as BendsSpace mentions, it would just stack and stack.

1 Like

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