I would like to turn it into game.Workspace.Part in the script.
I am trying to make a function that I send the array to, and then it returns the object referenced in the array. I am at a loss trying to figure this out. I was going to start with a for loop that cycles through the array but how would it ultimately create a path to the object? FYI the array can have any number of items in it and it will vary in-game.
FYI, you don’t need the game element as everything comes from it.
local instanceNames = {"Workspace", "Part"}
local currentPath = game:GetService(table.remove(instanceNames, 1))
for _, nextChild in instanceNames do
currentPath = currentPath:FindFirstChild(nextChild)
end
print(currentPath) -- workspace.Part
I already removed game from my array before running your code and it works fine. It’s just that because it only does FindFirstChild and since CurrentCamera is a property of workspace that contains a path to Workspace.Camera, that’s why it didn’t work. I just wrote some lines of code that replace CurrentCamera with Camera to solve the issue lol.
Hello!
Sorry for my late response I’ve just seen this post.
CurrentCamera is a property of workspace which returns a camera Instance. So it’s not actually a child of workspace.
This code should satisfy your needs for Instances other than properties for workspace.
--!strict
local Path: {string} = {
"Workspace";
"Part";
}
function PathToInstance(Array: {string}): (Instance?, number?) --// Returns nil if the Instance or service does not exist
local Instance: Instance = game;
for i = 1, #Array do
Instance = Instance:FindFirstChild(Array[i]);
if not Instance then return nil, i end; --> if instance couldnt be found return nil and the index where it failed.
end
return Instance;
end
print(PathToInstance(Path)) --> Output: Part Instance (which is parented to workspace)
The function I’ve provided returns nil and the index of where it failed if the instance couldn’t be found such as:
local Path: {string} = {
"Workspace";
"Patr"; --> Misspelled Part
}
print(PathToInstance(Path)) --> Output: nil, 2
Though I’m afraid it won’t help you with getting workspace.CurrentCamera.
FWIW: if you’re a Rojo/Wally user, check out import. This takes a string written like directories on your filesystem and breaks it down to use as an instance path. It also has configurable options and aliases that you can use to shortcut some common paths that your experience might use.