Cloning and Spawning an NPC freezes the game

So I was making an npc and then I cloned it to put it in the workspace, and when I clone it and put it in the workspace, it stutters.

Each of those stutters are when the NPCS spawn in.

Here is my NPC spawning code:

local AliensFolder = script.Parent:WaitForChild("CurrentAliens")

local MaxAliens = 10
local CurrentAliens = #AliensFolder:GetChildren()

local function SpawnAlien()
	
	local Parasite = game.ReplicatedStorage.Aliens.Parasites.Parasite:Clone()
	Parasite.Parent = AliensFolder
	Parasite:PivotTo(script.Parent.ParasiteSpawner.CFrame)
	spawn(function()
		wait(1)
		Parasite.Controller.Enabled = true
	end)
	CurrentAliens = #AliensFolder:GetChildren()
	
end

for i = 1, MaxAliens do
	SpawnAlien()
	wait(2)
end

AliensFolder.ChildRemoved:Connect(function()
	spawn(function()
		wait(math.random(2, 6))
		SpawnAlien()
	end)
end)

All of the AI Scripts are in the Parasite

Hi,
See if either one of these help.

  • I PivotTo before I Parent an NPC
  • Set the NPC PrimaryPart:SetNetworkOwner(nil)

I’ve tried both but none seem to work. Is it because I have code in the NPC itself?

Edit: It’s when I clone in any NPC it stutters. Is there a reason for this?

Code inside the npc itself should be fine. Once it’s parented to the workspace the code within the npc will start to run. Depending on your code inside the npc there might be a very small noticible delay before the npc starts moving.

Your code to spawn in the npc looks OK.

Check for spikes in the script’s activity (Script Performance), large spikes could cause stutters/frame drops/packet loss.

One of the most apparent (but not exactly “easy”) ways you could optimize is using Object Pooling.

As a side note, it might be beneficial to familiarize yourself with the task library for built-in functions like wait, spawn, and delay.

How I handle this, is I create the NPC and parent to the workspace, then clone the script into the NPC from storage and as a final step enable the script. The stored script is in a disabled state is never enabled until after being added to the NPC.

Why do you use spawn so much???

I use spawn so it doesn’t interrupt the other parts of the code by delaying it

I tried just cloning the NPC itself with no code in it to the workspace but it still lagged

There’s no reason you need that many spawns, especially the deprecated spawn function.
You don’t need a spawn here, can instead be changed to task.delay(math.random(2, 6), func() end)

This below can be changed into a task.delay function which is the point of delay.

This below should be truthfully changed to ParasiteSpawner:GetPivot() instead of CFrame to keep with usage.