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