Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Respawn script causing a lot of lag. Can help optimizing it?

I have here a respawn script that will respawn a mob (that it is parented to). thing is whenever the mob respawns my game just freezes for like 4 seconds, before returning to normal.

I do not want this to happen so all I want is a more optimized (less laggy) version of the script below:

local _M = require(script.Parent.MobConfig)
local Mob = script.Parent -- The mob
local Enemy = Mob.Enemy -- the Mob's Humanoid

MobClone = Mob:Clone() -- Clone the mob (the mob is an R15 rig so that might be the reason it lags)

function Respawn()
    if (not Mob) then return end
    wait(_M.RespawnTime)
    script.Parent:Destroy()
    MobClone.Parent = game.Workspace.MobHolder.GrassPeople -- the place the character respawns in
end    

Enemy.Died:Connect(Respawn)

1 comment

0

Maybe switch lines 10 and 11?

1 answer

I can't tell you why your script lags, it's mostly likely another reason, maybe you have connections that don't get GC'ed or maybe you have expensive functions running on the humanoid's death. Maybe it's the fact that you destroy the script's parent (and so does the script get destroyed) before parenting the mob to workspace.

I think it's better to use CollectionService coupled with Tiffany's Tag Viewer.

One way I would go about this using CollectionService is this way:

local CollectionService = game:GetService("CollectionService")
local connections = {}
local mob = game:GetService("ServerStorage").GrassMan -- or wherever you have a mob stored

function respawnMob()
	wait(respawnTime)
	mob:Clone().Parent = workspace -- no need for a holder when you have them all 
end

for _,mob in pairs(CollectionService:GetTagged("GrassPeople")) do
	connections[mob] = mob.Humanoid.Died:Connect(function()
		if not mob then return end
		mob:Destroy(); respawnMob(); connections[mob]:Disconnect() -- the ';' sign signifies an invisible new line so you can run multiple commands in one row
	end)
end
CollectionService:GetInstanceAddedSignal("GrassPeople"):Connect(function(mob)
	connections[mob] = mob.Humanoid.Died:Connect(function()
		if not mob then return end
		mob:Destroy(); respawnMob(); connections[mob]:Disconnect()
	end)	
end)
CollectionService:GetInstanceRemovedSignal("GrassPeople"):Connect(function(mob)
	connections[mob]:Disconnect() -- just a failsafe for if/when you :Destroy() the mob
end)

1 comment

0

alr, i'll look into this and see what i can do with it

This discussion is preserved as it was. New answers, comments, and votes are closed.