How do I make a function run while part is being stepped on and stop when stepped off

I want this while true do loop to run until the player steps off the part but I don’t know how, this is my code

e = script.Parent
e.Touch:Connect(function(hit)
		while true do
		local newPart = Instance.new("Part", game.Workspace)
		newPart.Size = Vector3.new(1,1,1)
		newPart.Material = "Glass"
		newPart.Color = Color3.new(0, 0.5, 1)
		newPart.Reflectance = 1
		newPart.Anchored = false
		newPart.CFrame = CFrame.new(0, 6.75, -60.5)
		wait(0.15)
	end
	if e.TouchEnded then
	end
end)

Right now it starts running when you step on it but doesn’t stop at all

Stepping on parts is an unreliable way to detect it, instead I suggest to make an invisible part and make it collidable.

Also this script only works if you make it a big part, which can touch the HumanoidRootPart, it’s also unreliable to detect multiple parts of the body, so instead we are targetting the RootPart.

local collisionPart = script.Parent
local touched, isRunning = false, false

local function start()
	if isRunning then return end 
	isRunning = true -- to stop other detections
	while touched do -- stops when nobody is touching
		local newPart = Instance.new("Part", game.Workspace)
		newPart.Size = Vector3.new(1,1,1)
		newPart.Material = "Glass"
		newPart.Color = Color3.new(0, 0.5, 1)
		newPart.Reflectance = 1
		newPart.Anchored = false
		newPart.CFrame = CFrame.new(0, 6.75, -60.5)
		wait(0.15)
	end
   isRunning = false -- this runs when the loop stops
end

collisionPart.Touched:Connect(function(hitPart)
	if hitPart.Name ~= "HumanoidRootPart" then return end
	touched = true
	start()
end)

collisionPart.TouchedEnded:Connect(function(hitPart)
	if hitPart.Name ~= "HumanoidRootPart" then return end
	touched = false
end)
1 Like