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

How can I make this more efficient?

So basically I want the player's walk speed to change whenever it is in the Terrain water. What I made bellow works, but I'd like it to be more efficient, and only change when the player is in/out of the water. I don't really know how to go about doing so, and I would really appreciate some help <3

game.Players.PlayerAdded:connect(function(Player)
Player.CharacterAdded:connect(function(char)
local humanoid = char:WaitForChild("Humanoid")
local drown = false

humanoid.Swimming:connect(function(swim)
if swim > 0 then drown = true
elseif swim < 1 then drown = false
end
end)

while wait(0.1) do
if drown then humanoid.WalkSpeed = 5
else
local found = game.Workspace:FindFirstChild(humanoid.Parent.Name.."'s_folder")
if found then
	humanoid.WalkSpeed = found.Speed.Value
end

end
end

end)
end)
****

Happy murica day!

1 answer

✓ Accepted answer

You can simply use the StateChanged event of the Humanoid to tell when the Human is swimming or when the human is not swimming. You can use it like so:

Humanoid.StateChanged:connect(function(_, State) --The StateChanged event has 2 parameters, the previous state and the current state. We only need to know the current state so we can use an "_" to take the place of an unused parameter
	if State == Enum.HumanoidStateType.Swimming then
		--Swimming code
	else
		--Not swimming code
	end
end)

Hope this helped!

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