How to do a while touching loop! - TUTORIAL

This is a tutorial because i couldnt find a actual forum telling you how to do it

local touching = false

script.Parent.Touched:Connect(function(hit) --checks if the player touched
	local player = game:GetService("Players"):GetPlayerFromCharacter(hit.Parent)
	if player then
		touching=true	
	end
end)

script.Parent.TouchEnded:Connect(function(hit) --checks when the player stopped touching
	local player = game:GetService("Players"):GetPlayerFromCharacter(hit.Parent)
	if player then
		touching=false	
	end
end)

coroutine.wrap(function()
	while touching do -- While touching loop
		task.wait()
		--Your script here
	end
end)()

Hope i helped (this is a repost because i did a mistake in the last post and couldnt delete it)

1 Like

Wrong topic btw. #resources:community-resources or #resources:community-tutorials if you add more explaining. Also you can always edit your topic and I’m pretty sure there are tutorials on loops.

Also you should put the loop inside the touch function so you’re not always checking until it touches.

One more thing you should check if the hit.Parent has a humanoid. This makes sure the player is an actual player.

2 Likes

Actually it makes sure they’re some sort of NPC or a player character. To ensure it’s a player character you must run game.Players:GetPlayerFromCharacter(hit.Parent) and check if it returns a player or nil. If it returns nil but it looks like a character(it has a humanoid, body parts, etc.) it’s probably an in-game NPC.

1 Like

Oops I misread thanks for correcting me.

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