Get Instance from Path

Hello I would like to know how can I get an instance from a path, like in this example:
Path: “ReplicatedStorage.Events.Shoot”
image

We can get the event and we can fire it for example.

Please elaborate… Do you need to get the Instance from a string?

It does not answer :(, imagine you have a TextBox with a path and I want to get the remoteevent from the box.

We can say this, imagine you have a box which contains the path and I want to get the instance/remote event here from this.

By the way I tried this:

local rs = game:GetService("ReplicatedStorage")
local path = script:GetAttribute("RemoteEvent")

local function parsePathRemote(path)
	local path_segments = string.split(path, ".")
	local object = game:GetService("ReplicatedStorage")

	for _, segment in ipairs(path_segments) do
		object = object and object[segment]
		if not object then
			break
		end
	end

	return object
end

local event = parsePathRemote(path)

You could use string.split(...) function from string library. First argument is the text (or path), and second argument would be “.”, because we want to split the string.

This function now will return multiple values in a table. So how to get this is with the first item you do

game[firstitem], and then continue adding on like this: game[firstitem][seconditem]
Use string.format or .. for this, and you will then get the instance.

1 Like

Yeah but my function is correct no :thinking: ?

If you mean how to convert the string “ReplicatedStorage.Events.Shoot” here’s an implementation:

local function pathToInstance(path: string): Instance?
	local names = path:split(".")
	if names[1] == "game" then table.remove(names, 1) end
	if #names == 0 then return nil end
	if names[1] == "workspace" then names[1] = "Workspace" end
	local success, inst = pcall(function()
		return game:GetService(names[1])
	end)
	if not success then 
		inst = game:FindFirstChild(names[1])
		if not inst then return nil end
	end 
	for i = 2, #names do
		inst = inst:FindFirstChild(names[i])
		if inst == nil then break end
	end
	return inst 
end

--All the following work:
print(pathToInstance("workspace.Baseplate"))
print(pathToInstance("Workspace.Baseplate"))
print(pathToInstance("game.Workspace.Baseplate"))
3 Likes

Thank you :slight_smile: ! Have a great day :).

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.