Problem with npc swimming animation

How to make it so that when an npc enters the water, he starts the animation of swimming, but there is a problem when an npc comes out of the water, the animation continues
script:

-- function onSwimming(speed)
	if speed > 0 then
		swimAnimTrack:Play()
	else
		swimAnimTrack:Stop()
	end
end

humanoid.Swimming:connect(onSwimming)
1 Like

humanoid.Swimming will not always fire with a speed of 0 when the player stops swimming, so I would recommend using another way

humanoid.StateChanged:Connect(function(oldState, newState)
	if newState == Enum.HumanoidStateType.Swimming then
		-- Play the animation
	elseif newState ~= Enum.HumanoidStateType.Swimming
	and oldState == Enum.HumanoidStateType.Swimming then
		-- Stop the animation
	end
end)