Drowning system works but has one issue that I cant seem to fix

I have a drowning system onside of a few parts (acting as water), and it works. The issue that I have though is that every time the player re-enters the water the speed of the drowning increases slightly until they start to drown instantly. There are no errors, this is why I’m super confused.


in the recording above you can see that the oxygen drains faster and faster each time

(sorry for all of the cuts, the video was too large at first)

and here is the script:

game.Players.PlayerAdded:Connect(function(plr)
	local losingOxygen = Instance.new("BoolValue")
	losingOxygen.Parent = plr
	losingOxygen.Name = "LosingOxygen"
	losingOxygen.Value = false
	local oxygen = Instance.new("IntValue")
	oxygen.Parent = plr
	oxygen.Name = "Oxygen"
	oxygen.Value = 30
end)

for i, water in pairs(workspace.Environment.WaterParts:GetChildren()) do
	if water:FindFirstChild("DoesntDrownPlayer") == nil and water:IsA("BasePart") then
		local plrs = {}
		water.Touched:Connect(function(hit)
			local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
			if plr and hit.Name == "Head" then
				plr:FindFirstChild("LosingOxygen").Value = true
				table.insert(plrs, plr)
			end
		end)
		water.TouchEnded:Connect(function(hit)
			local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
			if plr and hit.Name == "Head" then
				plr:FindFirstChild("LosingOxygen").Value = false
			end
		end)
		spawn(function()
			while true do
				for i, plr in pairs(plrs) do
					if plr:FindFirstChild("LosingOxygen").Value == true then
						plr:FindFirstChild("Oxygen").Value -= 1
					else
						plr:FindFirstChild("Oxygen").Value = 30
					end
					UpdateOxygen(plr, plr:FindFirstChild("Oxygen").Value, plr:FindFirstChild("LosingOxygen").Value)
					if plr:FindFirstChild("Oxygen").Value <= 0 and plr.Character.Humanoid ~= nil then
						plr.Character.Humanoid.Health -= 8
					end
				end
				wait(1)
			end
		end)
	end
end

function UpdateOxygen(plr, timeLeft, inWater)
	if plr then
		game.ReplicatedStorage.UpdateOxygen:FireClient(plr, timeLeft, inWater)
	end
end

If anybody knows how I can fix this, please let me know

2 Likes

You are adding the same player to the “plrs” table multiple times, every time the player touches the water he is added to the table.

image

Meaning that the script will trigger more than once for the same player and it will keep being triggered more and more and more until insta-kill

hope this helps :smiley:

3 Likes

Thank you! I cant believe I didnt see that before lol. I was able to fix this simply by adding an if statement before inserting the plr into the table checking if they were already in there

3 Likes

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