I want to set a variable to an object deep within the script and don't want to type a bunch of WaitForChild commands

I am wondering if this is an efficient way to do it.

local dialogchoice

while not dialogchoice do
	wait()
	pcall(function()
		dialogchoice = script.Parent.Dialog.DialogChoice.DialogChoice.DialogChoice.DialogChoice.DialogChoice.DialogChoice
	end)
end

The script is in the head of an NPC.
I am just wondering if this is an efficient way to do it or if there’s a better way.

Well this is fired at the start of the game, but nvm anyway, I found a better way to do this. Thanks a lot anyway!

Is it necessary to have the dialog choice called “DialogChoice”?
Would it not be worth numbering them all via level?
eg

script.Parent.Dialog.DialogChoice1
script.Parent.Dialog.DialogChoice1.DialogChoice2
script.Parent.Dialog.DialogChoice1.DialogChoice2.DialogChoice3

and so on and so on.
After that, all you should need to do is call;

local Dialog = script.Parent.Dialog
local DEPTH = 1 -- or 2,3,4... however deep you're trying to search.
local dialogchoice = Dialog:FindFirstChild("DialogChoice"..DEPTH, true)
--[[FindFirstChild(OBJ, true) will search through all descendants to find a value. 
If nothing exists, it returns nothing]]
4 Likes