How to slowly kill a player ONLY when they are touching a part?

  1. I need to make a player that is touching on a non-team zone to take damage by -5 HP per second

  2. With scripts I’ve looked for, player does slowly die in a non-team zone but when they leave that zone they continue to take damage. When the player out of that no-touch zone, I want them to stop taking damage

  3. I went through DevForums and was able to find a script that slowly kills players but wasn’t able to find one that would somehow end that loop when they are not touching the zone

This is what I currently have, what should I add to stop a player from taking damage when they are not touching the part anymore?

local team = game.Teams.Red
local door = script.Parent

door.Touched:Connect(function(hit)
	local humanoid = hit.Parent:FindFirstChild("Humanoid")
	if humanoid then
		local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
		if plr.Team ~= team then
					for i = humanoid.Health, 0, -5 do
			humanoid.Health = i
			print(humanoid.Health)
			wait(1)
			end
		end
	end
end)

SlowDamage.rbxl (54.6 KB)

--!strict

--// Services

local teams = game:GetService("Teams")
local plrs = game:GetService("Players")

--// Other Variables

local DAMAGE_AMOUNT: number = 5
local DAMAGE_INTERVAL: number = 1
local ALLOWED_TEAM: Team = teams.Red

local damagePart = script.Parent
local currentTouchingParts = {}

--// Main Code

damagePart.Touched:Connect(function(part)
	currentTouchingParts[part] = true
end)

damagePart.TouchEnded:Connect(function(part)
	currentTouchingParts[part] = nil
end)

while task.wait(DAMAGE_INTERVAL) do
	local damageThisTime: {[Humanoid]: boolean} = {}
	for toucher, _ in currentTouchingParts do
		local humanoid = toucher.Parent:FindFirstChildOfClass("Humanoid")
		if not humanoid or humanoid.Health == 0 then
			continue
		end
		local player = plrs:GetPlayerFromCharacter(humanoid.Parent)
		if not player or player.Team == ALLOWED_TEAM then
			continue
		end
		damageThisTime[humanoid] = true
	end
	
	for humanoid, _ in damageThisTime do
		humanoid:TakeDamage(DAMAGE_AMOUNT)
	end
end
3 Likes

Thank you so much, it works just how I need it to be! :+1:

2 Likes

Hi again, I found one tiny problem.

So I made a script to be able to enable/disable that no-touch zone part, however I even disabled CanTouch as part of the toggle script but it still damages non-team members even when the part is Transparent and CanTouch is disabled

And also when I leave that No-Touch zone while its “disabled” I still get damaged

Clear the touching parts when CanTouch is set to false

damagePart:GetPropertyChangedSignal("CanTouch"):Connect(function()
	if damagePart.CanTouch == false then
		currentTouchingParts = {}
	end
end)

Although it is better to have a BoolValue to switch it instead of mingling with CanTouch:
SlowDamage2.rbxl (55.2 KB)

1 Like

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