Hey, so I’ve been wondering about when it is most appropriate to use both WaitForChild() and FindFirstChild() and haven’t found a clear answer. I’ve looked at some Devforum posts on the subject (most of which were painstakingly long and filled with a lot of irrelevant information.) I also saw in the replies, several people were claiming the posts to be inaccurate.
So I guess what I want to know is how to best utilize these. When should they be used and when should they be avoided?
I saw in some of the posts, people said to only use WaitForChild() if you know the object isn’t yet in the game but is going to eventually be. I find this interesting because in my game, I have a local script which refers to a model in the workspace. This model and its descendants exist from the very start of the game. Yet if I exclude WaitForChild(), the code errors.
The code:
local trap1Event = game:GetService("ReplicatedStorage"):WaitForChild("TrapEvents"):WaitForChild("Trap1Event")
local spike1 = game.Workspace:WaitForChild("Trap1Components"):WaitForChild("SpikeWall1"):WaitForChild("Spikes")
local spike2 = game.Workspace:WaitForChild("Trap1Components"):WaitForChild("SpikeWall2"):WaitForChild("Spikes")
As you can see, there are a lot of WaitForChilds. Is this excessive? I know for a fact if I remove the WaitForChild before “Spikes” the code will error because “Spikes” apparently doesn’t exist…
Now, moving onto FindFirstChild()
If you look at pretty much any kill brick in the Toolbox, you will see at least one line of code that looks something like this:
local humanoid = hit.Parent:FindFirstChild("Humanoid")
or
if hit.Parent:FindFirstChild("Humanoid") then
Are these scripts correctly using FindFirstChild?
Any help is much appreciated!
(Sorry if this post is worded weird, I’m extremely tired)