Soccer game loop causes lag

I know I’m supposed to upload a file but this will work better.

Basically, I just started making a soccer game, and I am using a coroutined while loop to check if the a player is touching the ball, and if so, weld it to him.

Issue is, the loop is generating lag (game has tiny freezes every few frames).

CODE:

local Players = game:GetService("Players")
local ball = workspace:WaitForChild("Ball")
Players.PlayerAdded:Connect(function(player)
	player.CharacterAdded:Connect(function(character)
		local animate = character:WaitForChild("Animate")
		animate:WaitForChild("run"):WaitForChild("RunAnim").AnimationId = "rbxassetid://117305406261035"
		animate:WaitForChild("walk"):WaitForChild("WalkAnim").AnimationId = "rbxassetid://117305406261035"
	end)
end)
--PART CAUSING LAG (I think it may be related to the and in the while statement)
local getBall = coroutine.create(function()
	while task.wait() and ball:WaitForChild("PossessorName").Value == "" do
		local nearParts = workspace:GetPartBoundsInRadius(ball.Position, 6)
		for index, nearPart in pairs(nearParts) do
			if nearPart.Name == "HumanoidRootPart" then
				ball.Parent = nearPart.Parent
				local motor6D = Instance.new("Motor6D")
				motor6D.Name = "Ball"
				motor6D.Part0 = nearPart
				motor6D.Part1 = ball
				motor6D.Parent = nearPart
				
				break
			end
		end
	end
end)
coroutine.resume(getBall)

Every time you loop, you are creating a new Motor6D without deleting any of the old ones, in just a few seconds you are creating hundreds or even thousands of Motor6D instances!

Try keeping track of your Motor6Ds in a variable or table and destroy them whenever they are no longer needed.

2 Likes

i forgot to change the possessor name to the players, thanks!