Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Should I use game.Players or game:GetService("Players")?

I have used Roblox Lua some time, and in every script I ever write, when I want to access, let's say, Players, I do

local players = game.Players

However, I have frequently seen others use

local players = game:GetService("Players")

instead. Is this "better" or more efficient in any way? To me, it just seems a bit more complicated, and I only use :GetService() for Services like TweenService or DebrisService, which aren't found in the Explorer.

3 answers

✓ Accepted answer

game.Players indexes a child of game named Players. If, for some reason, you renamed the Players service, game.Players will either index a nil value or, if a different child has the name Players, it will index that child. Thus, GetService() is considered the standard go-to for referencing services. GetService(serviceName) returns the service with the name serviceName. For every service (except the Workspace and any service that can't be retrieved), GetService() is a MUST. (You can do game:GetService("Workspace"), although doing so is mostly irrelevant because of the workspace shared variable.)

1 comment

0

Thanks, this helps. so, in other words, don't use 'game.Players', and use 'workspace' instead of 'game.Workspace', right?

If you (accidentally or on purpose) change the name of Players service in your game (and you can), game:GetService("Players") will still work, while game.Players will not.

I ever use game:GetService("Players") because this avoids to give some bugs,for exemple,sometimes the script runs before to reload the game.PlayerService,do you understood now?

This discussion is preserved as it was. New answers, comments, and votes are closed.