Ad
Still have questions? Join our Discord server and get real time help.
Log in to vote
0

How would get a players' location from a global script?

Asked by 3 years ago

I am trying to get the players' location using a global script, this is what I have written:

local location = Vector3.new(0,0.5,0)
local playerName = script.Parent.Parent.Parent.Parent.Name
local playerLocation = game.Workspace.playerName.UpperTorso.Position

print(playerLocation)

I don't know why but it keeps saying that playerName is an invalid member of Workspace. Should I put a wait so that ROBLOX has time to load the character? What do I do? Thank you/

3 answers

Log in to vote
1
Answered by
cfiredog 259 Moderation Voter
3 years ago
Edited 1 year ago

You can use the PlayerAdded event and then wait for the player's character like so:

game:GetService("Players").PlayerAdded:Connect(function(player)
    local character = player.CharacterAdded:wait()
    local position = character:WaitForChild("HumanoidRootPart").Position
end)

If this answers your question, please accept this as the best answer!

0
Thanks for posting this! I was able to get this to work by replacing the '.' with ':' after 'game.' Just adding a little context; the reason you have to use the 'Players' service and wait for an event is because your player is not initially in the game, so you have to wait for the event to fire before getting your position. funitude 5 — 2y
Ad
Log in to vote
0
Answered by
thesit123 503 Moderation Voter
3 years ago

Put the Global Script in Workspace. Then try this code:

game.Player.PlayerAdded:Connect(function(Plr) -- Player is added
Plr.CharacterAdded:Connect(function(Char) -- Players' character added

local location = Char:WaitForChild("UpperTorso").Position -- wait for uppertorso to appear then get the position

end)
end)
Log in to vote
0
Answered by 3 years ago
Edited 3 years ago

Change the code to

local location = Vector3.new(0,0.5,0)
repeat wait()

until script.Parent.Parent.Parent.Parent.Character
local playerName = script.Parent.Parent.Parent.Parent.Name
repeat wait()

until game.Workspace.playerName.UpperTorso
local playerLocation = game.Workspace.playerName.UpperTorso.Position

print(playerLocation)
0
playername wasn't valid again dreameryoutubeREAL 3 — 3y

Answer this question