What's the best way for getting a text label inside multiple models?

i’m trying to access my TextLabel but i feel like doing this is super inefficient, are there any better ways?

local Plots = workspace.Plots

-- ._.
local plot = Plots:FindFirstChild("plot")
local SignModel = plot:FindFirstChild("SignModel")
local Sign = SignModel:FindFirstChild("Sign")
local SurfaceGui = Sign:FindFirstChild("SurfaceGui ")
local TextLabel = SurfaceGui:FindFirstChild("TextLabel")

why are you using FindFirstChild so much?

local Workspace = game:GetService("Workspace");

local PlotsFolder = Workspace.Plots;

local plot = PlotsFolder.plot;
local SignModel = plot.SignModel;
local Sign = SignModel.Sign;
local SurfaceGui = Sign.SurfaceGui;
local TextLabel = SurfaceGui.TextLabel;


-- Code Here --


FindFirstChild Documentation

I’m not sure what other purpose would warrant you using those variables, but I’ll assume you only ever want the TextLabel. I will also assume that you will have multiple plots in your game. In that case, you can:

  1. Take the assumption that one plot’s model hierarchy is the same for all of your plots. In that case, just access the TextLabel normally:
local TextLabel = Plots.plot.SignModel.Sign.SurfaceGui.TextLabel

In a for loop, the idea is the same:

for _, plot in ipairs(Plots:GetChildren()) do
	local TextLabel = plot.SignModel.Sign.SurfaceGui.TextLabel
end
  1. If your plot’s hierarchy will differ from your current setup, you can add an ObjectValue under each plot model (specifically as a direct child of the plot model, not a grandchild), with the value being named “SignLabel” or something similar, and with its .Value assigned to the TextLabel. Then, you can simply access the TextLabel via SignLabel.Value.
local TextLabel = Plots.plot.SignLabel.Value

However, I suggest you should always stick with directly accessing the objects (with or without a variable) without using FindFirstChild and its variants or WaitForChild if you are certain that the path and the object will stay the same throughout the entire game’s session. The only times you would want to use those methods is if the object with a specific name/class you are looking for may or may not exist, or if you’re waiting for an object with a similar name to appear, respectively.

1 Like

If you can guarantee that there will only be one TextLabel like that, then you could do

local TextLabel = plot:FindFirstChild("TextLabel", true)
3 Likes

that’s a great response, i ended up using a for loop which i should’ve thought about sooner. thanks a million for your help y_vrn! :slight_smile:

1 Like

i should’ve done that as well. i think i had that before but i removed it due to a problem with my code but the recursive parameter is extremely helpful. thanks for your help mate! :slight_smile: