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

How Can You Wait Until Something Occurs?

Asked by 5 years ago

I want to add a wait until a particular part in the workspace is destroyed. I have never made a "wait until" loop by myself before, so I'd appreciate seeing the general format. Thanks in advance.

3 answers

Log in to vote
0
Answered by 5 years ago
1While true do
2if not game.Workspace:FindFirstChild("NameOfPart") then
3--do something
4end
5wait(0.1)
6end
Ad
Log in to vote
0
Answered by
SurfedZ 36
5 years ago
1workspace.ChildRemoved:Connect(function(Child)
2    if Child.Name == "InstanceName" then
3        -- Your code
4    end
5end)
Log in to vote
0
Answered by 5 years ago

If you have a reference to the part that is going to be destroyed, it is better to do:

1local part = workspace.PartToBeDestroyed -- for example
2part.AncestryChanged:Wait() -- this waits for AncestryChanged to fire with any arguments - if you're sure that the part's parents won't change, this is all you need (and it is more efficient than loops since you don't have code running 30 times a second). If the parent can change around with the part being destroyed, connect to the event:
3 
4local con -- connection
5con = part.AncestryChanged:Connect(function(child, parent)
6    if parent ~= nil then return end
7    con:Disconnect()
8    -- The part has been destroyed
9end

Tracking the connection made by Connect like that is unnecessary if you're connecting to an event owned by an object that will be Destroyed, but in the case that part was only de-parented rather than Destroyed (I believe this happens if the server destroys an object - the client only deparents it), it guarantees that the event will be cleaned up (preventing a memory leak).

Answer this question