How do i make while loop stop when i press 1

im trying to make something out of my imaginary
So basically when you press e you summon a part
if you press 1 the part goes to where your mouse is like a projectile

when i press 1 it just clones and go to the player
im trying to stop the while loop

here is a video of it:

normalscript:

local rem = game:GetService("ReplicatedStorage").RemoteEvent
local REM2 = game:GetService("ReplicatedStorage").remotevent2

local function onevent(plr)
	local char = plr.Character or plr.CharacterAdded:Wait()
local head = char:WaitForChild("Head")
	local part = game:GetService("ReplicatedStorage").Part
	local clone = part:Clone()
	local bp = Instance.new("BodyPosition",clone)
	
	bp.MaxForce =  Vector3.new(48000,48000,48000)
	
	clone.Parent = head
	REM2:FireClient(plr)
	while task.wait() do
		
		bp.Position = head.CFrame * Vector3.new(0,5,0)

	end
end

local function onevent2(plr,mouse)
	local char = plr.Character or plr.CharacterAdded:Wait()
	local head = char:WaitForChild("Head")
	local clone = head:WaitForChild("clone")
	local bv = Instance.new("BodyVelocity",clone)
	bv.MaxForce = Vector3.new(1,1,1) * 3000
	bv.Velocity = Vector3.new(clone.Position,mouse)
	
end


rem.OnServerEvent:Connect(onevent)
REM2.OnServerEvent:Connect(onevent2)

local script one:

local uis = game:GetService("UserInputService")
local rem =  game:GetService("ReplicatedStorage").RemoteEvent
local debounce = false
local plr = game.Players.LocalPlayer
uis.InputBegan:Connect(function(input,istyping)
	
	if istyping then return end
	if input.KeyCode == Enum.KeyCode.E then
		rem:FireServer()
	end
end)

local script 2:

local rem2 = game:GetService("ReplicatedStorage").remotevent2
local rem3 = game:GetService("ReplicatedStorage").RemoteEvent3
local rem = game:GetService("ReplicatedStorage").RemoteEvent
local uis = game:GetService("UserInputService")

rem2.OnClientEvent:Connect(function(plr)
	local plrr = game.Players.LocalPlayer
	uis.InputBegan:Connect(function(input,istyping)
	
		if istyping then return end
		if input.KeyCode == Enum.KeyCode.One then
			local mouse = plrr:GetMouse()
			
			rem:FireServer(mouse.Hit.p)
			print("fired")
		end
	end)
end)
1 Like

You can use a bool value to break the while loop

However the way you are doing this is heavy on performance. Instead of this you can use Align Position, which does the same thing you are doing in this while loop, but much more efficiently. And it will be easier to stop and redo

2 Likes