KillBrick Loop Help

Hate being the noob lol, I attempted to create a killpart script from scratch that takes incremental damage over time whilst a player is touching the part, but I’m stuck with the loop. Once I touch the part, it doesn’t matter if I leave the block, it keeps damaging the player.

How far off was I?

--//Variables
local Human = game:GetService("Players")	
local Damage = 5

--//Functions
script.Parent.Touched:Connect(function(hit)
	Human = hit.Parent:FindFirstChild("Humanoid") 
	if Human then
		while Human do
			Human.Parent.Humanoid:TakeDamage(Damage)
			wait(1)
			if Human == nil then
				break
			end
		end
	end
end)

2 Likes

The Humanoid will still exist after going off the part, you should instead check if the player still touches the part.

2 Likes

If you want, I can send you an improved version of the script in a few minutes.

2 Likes

You can if you wish too, how far off was I?

1 Like

You still get damaged because of the wait(1). Remove the loops, since .Touched event fires more times without a debounce.

1 Like

The original script I was using was this, but it only damaged the player when they moved.

script.Parent.Touched:Connect(function(hit)
	local humanoid = hit.Parent:FindFirstChild("Humanoid") 
	if hit.Parent.Humanoid:TakeDamage(5) then
		
	end
end)
1 Like

I don’t recommend that. A loop would be much more exact to always deal the same amount of damage.

1 Like

Use a touchEnded event to change a bool value (whether he is touching or not) and have the while loop by itself at the end of the script, you were close to getting it right!

2 Likes

Final solution I guess.

local damage = 5--I'm using camelCaseNotation if the variable isn't an instance.

script.Parent.Touched:Connect(function(Hit)
	local Humanoid = Hit.Parent:FindFirstChild("Humanoid") 
	if not Humanoid then return end -- Exit the function if there's no Humanoid at all.
	while table.find(script.Parent:GetTouchingParts(),Hit) do--Here I check if "Hit" is still a touching part.
		Humanoid:TakeDamage(damage)
		wait(1)
	end
end)
5 Likes

Hi!

I would like to add, that the correct way of telling if Humanoid is nil is not

if Humanoid  == nil then return end

But instead

if not Humanoid then return end
4 Likes

I thought that wouldn’t work since nil kind of “exists” or however to describe it. Thank you! I’ll edit my post.

1 Like

Yea nil does exist, but so does false. Both will return “false”. :smiley:

3 Likes