What do you want to achieve?
I need to get the player from workspace. For example: game.Workspace.YOURUSERNAME.HumanoidRootPart
What is the issue?
game.Players.PlayerAdded:Connect(function(player)
print(player.Name) --this prints as it should
local playername = player.Name
end)
local f = game.Workspace.playername --I want to be able to do this
When I try to do something with the variable f, (Like f.HumanoidRootPart) I get this:
I understand why this is happening, its thinking that im looking for a part or something in workspace called “playername”, but it doesn’t exist. How do i make it use the variable instead?
What solutions have you tried so far?
I’ve tried the developer hub and a regular google search, but I got nothing useful since I have no idea what I should look up.
Use Player.Character to get the player’s character from the workspace
game.Players.PlayerAdded:Connect(function(player)
print(player.Name) --this prints as it should
local playername = player.Name
local char = player.Character or player.CharacterAdded:Wait() --Get the character of the player`
print(char.Name)
end)
Or to make it work as you want it to. to get a part via a variable.
local part = workspace[playername]
the . operator is only used for indexing names or properties, you must use square brackets to search by string
First off, playername is local to the event-connection scope, so I am surprised this even worked. To the point:
to access a players character through its name, you could simply do
game.Players.PlayerAdded:Connect(
function(Player)
local PlayerName = Player.Name
-- little sanity check to avoid any complications with the character
-- not being loaded in yet
Player.CharacterAdded:Wait()
local Character = workspace[PlayerName]
end
)
-- But, you might just be better off accessing the players character directly like so:
game.Players.PlayerAdded:Connect(
function(Player)
local PlayerName = Player.Name
Player.CharacterAdded:Wait()
local Character = Player.Character
end
)