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

How to make this script more efficient?

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

1 comment

0

A UFO could appear inside any object in the workspace? How?

1 answer

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.

3 comments

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.

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.

0

I tried this script and it did not remove the UFO when it got added to the workspace.

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