Which one is better?

Hi, I would like to ask which functions are better by optimization and overall
instance and Cake are examples.

local Cake = instance:WaitForChild("Cake")
repeat
   wait()
until instance.FindFirstChild("Cake")
local Cake = instance.Cake
instance.ChildAdded:Wait() -- Cake is the only instance that will be added.
local Cake = instance.Cake
local Cake = instance.ChildAdded:Wait()

Thanks for your response.

3 Likes

Gotta be the first one, the other examples are just unnecessary and I don’t think it effects that much optimization wise. The second will for sure take a bit longer to get due to the wait however not by much. Plus I’m not sure how consistent .ChildAdded is, as in what if the child is already loaded before the event is connected. I would just stick to :WaitForChild()

2 Likes

I think these are circumstantial.

If the game is loading and a function like playeradded is called and it needs something specific then that’s practical use for WaitForChild but like if a script needs a part to be created before it moves on that might be a better example of why you’d use the repeat code, though its kind of expensive to use. Not certain the last one is feasible.

1 Like
local Cake = instance.Cake or instance.ChildAdded:Wait()
1 Like
local Cake = instance:WaitForChild('Cake', math.huge)
1 Like

if you are waiting for it and you expect it to be added soon (a bit after the script runs) then WaitForChild without a timeout is fine

if you dont think it will always be there, then using WaitForChild with a timeout would be good

if you want it to do something everytime something is added, then use ChildAdded on its parent

WaitForChild was made specifically for waiting for stuff, so its optimized for this, shouldnt really use anything else to wait for a child object

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.