Get child using a string, not a property

Hello, how could I get a child of an object using the object[childName] (childName is obviously a string) instead of a property? I need to avoid using object:FindFirstChild() because this code is running in a heartbeat loop for performance reasons

Do you mean something like this?

local function GetChild(parent: Instance, childName: string) : Instance?
   local _, child = pcall(function()
       return parent[childName]
   end)

   -- Makes sure the returned value is an Instance
   return typeof(child) == "Instance" and child or nil
end
1 Like

From what I understand, using FindFirstChild is just as fast as using the method you explained. It won’t cause any performance issues and should work fine. If I were you, I would just go with FindFirstChild, and if it does end up being a performance issue, reply to this and I’ll try to get back to you.

1 Like

Your whole code can be replaced with a better alternative, the FindFirstChild method. It is better because it will search directly in the children table, ignoring all properties. If you had a Frame instance with a child named “Transparency”, your function would have returned nil if you wanted to find that child. And no, FindFirstChild won’t cause any performance issues even in the Heartbeat connection. In fact, your implementation is not just worse, it is slower. There might be a more efficient way instead of using FindFirstChild every frame though, as it sounds like a lazy solution.

1 Like

I’m well aware, OP said they didn’t want to use FindFirstChild

1 Like