How Can I Use A Variable As A Location?

Hello! I was wondering how I can use a Variable as a Location

Example:

local PLR = script.Parent.Parent.Box.Text
game.Players.PLR.PlayerGui.Example:Destroy()
3 Likes

PLR is a string you got from the textbox. You can use it in your scripts to find certain objects:

game.Players[PLR].PlayerGui.Example:Destroy()

If you want to use it as a location, use:

local PLR = game.Players[script.Parent.Parent.Box.Text]
PLR.PlayerGui.Example:Destroy()
5 Likes

Why the brackets?
(30 characters)

You use the brackets because they are used for indexing, for example, if you have

game.Players.PLR.PlayerGui.Example:Destroy() 

script will recognize it as “PLR”, whereas if you use

game.Players[PLR].PlayerGui.Example:Destroy()

then the script will recognize it as the PLR variable which can be to whatever you set it to be.

5 Likes

You can also use the FindFirstChild method, this’ll return nil if the Child was not found.

For example:

local Player = game:GetService("Players"):FindFirstChild(script.Parent.Parent.Box.Text);

if (Player) then --// Instances evaluate to true, nil evaluates to false
    Player.PlayerGui.Example:Destroy();
end

P.S: If you’re attempting to edit another Player’s PlayerGui from a LocalScript it will not replicate furthermore a RemoteEvent will be required.

3 Likes

Are you referring a Location as the path to an Instance or an actual Vector3 location on the X,Y,X axis?

From what you have listed, you are misusing the path of an object. I’m 100% assuming that your LocalScript is inside of your PlayerGui which means you don’t need to use game.Players.LocalPlayer.PlayerGui as it’s already parented to the PlayerGui.

Example:

local Button = script.Parent.Parent:FindFirstChild("Box") -- The variable is defined as the path / object
Button:Destroy() -- Uses the variable Button, destroys it when this is called

To get the path of an object, you can call :GetFullName() on an instance, which will return the path of said instance.

Example:

local Button = script.Parent
print(Button:GetFullName()) -- Will output: game.Players.desinied.PlayerGui.ScreenGui.TextButton
1 Like

yeah, using [ ] bracket operators for indexing is quick but it is prone to error, instance:FindFirstChild() has a larger overhead than direct indexing and will not error if an object doesn’t exist.

@Aiden_12114 you can use a variable as a reference; that’s basically the whole point of a variable.

Is your question something else?

2 Likes