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

How to make this script more efficient?

Asked by 8 years ago

I tried making a loop so every time a UFO is found in workspace, it gets removed. This is extremely inefficient so what's the best, most efficient way to make the UFO get removed?

while true do
    for k,v in pairs(game.Workspace:GetChildren()) do
        if v.Name == 'UFO' then
            v:Destroy();
        end;
    end;
end
0
A UFO could appear inside any object in the workspace? How? Validark 1580 — 8y

1 answer

Log in to vote
0
Answered by 8 years ago

There is an event which fits perfectly for your scenario called ChildAdded:

local debris = game:GetService("Debris")

game.Workspace.ChildAdded:connect(function(child)
    if child.Name == "UFO" then
        debris:AddItem( child,  0 )
    end
end)

I used debris service instead of destroy, because if you try to destroy at same time when it's added, it would error, since it's still trying to parent it. Adding wait() before destroying it would work as well, but I wished to do it this way.

0
Spawn(function() child:Destroy() end) -- destroys the item without using debris, also I would give DescendantAdded as an alternative in-case the UFO spawns in a model in the workspace. DevSean 270 — 8y
0
Spawn might cause unnescessary slowdown. For example, you have a heavily loaded thread that runs main game logic, animating many parts and moving things around, so that would delay the execution of spawn function due to the nature of Lua thread managing. Using debris would trust that onto C API. ZarsBranchkin 885 — 8y
0
I tried this script and it did not remove the UFO when it got added to the workspace. Precisionly 103 — 8y
Ad

Answer this question