How would I Clean Up Old While Loops that is not useful anymore

So i am making a BoatSpawner that uses a Gerstner wave system and when i spawn a boat it runs a while loop that calculates the boyancy for the ship.

The problem is that every time i spawn a new ship a while true loop spawns and the old one dosent get cleaned up. And it makes the game laggy. And i only wanna clean up the loop when the boat is deleted.

My script waits on a remote Event with information on which ship it is. Then a function clones the ship that got requested. After that a while true loop starts to calculate the boyancy of the Boat on the gerstner Waves. But I want to Achieve that the loop gets cleaned up when the boat is removed from the game.

Heres the code:

-- GameServices 
local RS = game:GetService("ReplicatedStorage")

while not _G.WavesLoaded do
	wait()
end
wait(0.01)

local function SpawnBoat(ShipModel)
	
	local Ship = ShipModel:Clone()
	Ship.Parent = game.Workspace.SpawnedShips
	
	while true do
		
		local Main = Ship.Main
		local FrontY = _G.GetHeight((Main.CFrame*CFrame.new(0,0,-40)).Position)
		local BackY = _G.GetHeight((Main.CFrame*CFrame.new(0,0,50)).Position)

		local FrontP = Vector3.new(Ship.Front.Position.X,FrontY,Ship.Front.Position.Z)
		local BackP = Vector3.new(Ship.Back.Position.X,BackY,Ship.Back.Position.Z)

		local RightY = _G.GetHeight((Main.CFrame*CFrame.new(10,0,0)).Position)
		local LeftY = _G.GetHeight((Main.CFrame*CFrame.new(-10,0,0)).Position)

		local Dif = FrontP-BackP
		local Mid = BackP+Dif/2

		local ShipHeight = _G.GetHeight(Main.Position)

		local x,y,z = Main.CFrame:ToOrientation()

		Main.BodyPosition.Position = Vector3.new(0,6.5,0)


		local AngX = math.atan2((FrontY-BackY), 90)
		local AngZ = math.atan2((RightY-LeftY), 20)
		Main.BodyGyro.CFrame = CFrame.Angles(0,y,0) * CFrame.Angles(AngX,0,AngZ)
		
		game:GetService("RunService").Stepped:Wait()

	end

	
end

local SpawnShipsRemote = RS:WaitForChild("SpawnShipsSystem"):WaitForChild("SpawnShipEvent")

SpawnShipsRemote.OnServerEvent:Connect(function(plr,Position)
	SpawnBoat(RS.SpawnShipsSystem:WaitForChild("Ships").Ship)
end)




Heres a intresting video on my work btw:
https://streamable.com/70sv1q

You can do like while Ship do end, where Ship is an instance you are reffering to. It checks if ship exists each time and if it doesn’t the loop breaks

2 Likes

I tried that before but i dont know why it did not work then hmm let me try again.

your ship must be deleted with Ship:Destroy() in order to work as well

1 Like

ohh i dont know i actually just deleted it while in game

1 Like

that works too, but you must do it from server side because you are probably using server script

2 Likes

Ohh well it works tysm. Lol i have calculted gerstner waves but forgot about server side

1 Like

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