Pet follow system not working

Hi, I have a problem with my pet follow system, for some unknown reason my pets are bugging out, and are causing lag.

Code:

local RunService = game:GetService("RunService")
local Players = game:GetService("Players")

local Player = Players.LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()

local HumanoidRootPart = Character:WaitForChild("HumanoidRootPart")
local SpawnPets = game.Workspace:WaitForChild("SpawnPets")

local Spacing = 4
local Pets = {}

RunService.Heartbeat:Connect(function(DeltaTime)
	if SpawnPets:FindFirstChild(Player.Name) then
		for _, Pet in SpawnPets[Player.Name]:GetChildren() do
			table.insert(Pets, Pet)
		end
		local columns = math.floor(math.sqrt(#Pets))
		local offset = Vector3.new(-columns / 2 * Spacing + Spacing / 2, 0, 4) 
		for i, pet in Pets do
			i -= 1
			local x = i % columns
			local z = math.floor(i / columns)
			pet.CFrame = pet.CFrame:Lerp(HumanoidRootPart.CFrame * CFrame.new(offset + Vector3.new(x, 0, z) * Spacing), 0.1)
		end
	end
end)
for _, Pet in SpawnPets[Player.Name]:GetChildren() do
	table.insert(Pets, Pet)
end

Why are you doing this every heartbeat? This will insert the same pets thousands of times, if you print the Pets table you will probably see thousands of the same pets, try doing the same loop but outside the heartbeat.

1 Like

Thanks for the help i did not know that :slight_smile:

1 Like

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