How to detect if a player is swimming in water?

I am trying to make a script in StarterCharacterScripts that will do small amounts of damage continuously while the character is in water. I don’t want to have to set up Region’s to do this. From looking at another post I saw this code and modified it to print out when the player is in water, which it does. The issue is that it only prints it once when I first touch the water or if I jump out and back in.

This is what I tried:

local char = script.Parent

while true do
	local ray = Ray.new(char.HumanoidRootPart.Position, char.HumanoidRootPart.CFrame:vectorToWorldSpace(Vector3.new(0, -5, 0)) )
	local hit, position, normal, material = workspace:FindPartOnRay(ray,char)
	if material == Enum.Material.Water then
	  warn("In Water")
	end
	wait()
end
2 Likes

if Humanoid:GetState() == Enum.HumanoidStateType.Swimming then

end

26 Likes

Oh jeez, I complicated it way too much, thank you.

2 Likes

no problem lol, i over complicate a lot of stuff on accident too

HI, did you get this to work, I put it as a script in serverscript service, and it only fires a few times, even when i move out of the water and run, then go back in to the water… it does not fire again…
I also tried it in the work space

Consider StateChanged. Depending on what kind of system you’re making that relies on the character swimming, you can use a LocalScript instead of a server one. If it’s game-critical stuff or shouldn’t be handled by the client, then you can use the server.

Naturally the if statement would only run once. You should provide details if you’re looking for help with something, because we can’t see what you’re doing otherwise. By details I mean also including the code you’re currently working with.

Hi,
Thank you for replying, I was able to figure out that piece, but now looking into another challenge, basically detecting if a player is on the surface of the water, ie in swimidle (which is still in the swimming state), or swimming on the surface, or near the surface, because I want to turn of a swimming effect, when they are in these conditions.

I posted a new post, here, and looking for ideas as to how to best approach playing around to figure it out.

This won’t work for me. Is it due to me using a localScript?

No it will work better with a localscript. You must be doing something wrong, show me your script and ill help you out