Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by
NGC4637 602 Moderation Voter
3 years ago

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)
0
Maybe switch lines 10 and 11? radiant_Light203 1166 — 3y

1 answer

Log in to vote
1
Answered by 3 years ago

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)
0
alr, i'll look into this and see what i can do with it NGC4637 602 — 3y
Ad

Answer this question