New: Nitro Boost our Discord server and receive full donation perks here on the website! Join the Scripting Helpers Discord Server to learn more! You can also Support on Patreon as always.
Ad
Still have questions? Join our Discord server and get real time help.
Log in to vote
0

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

Asked by 3 months ago
Edited 3 months ago

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

Log in to vote
1
Answered by
BashCaster 2370 Moderation Voter Community Moderator
3 months ago

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.)

0
Thanks, this helps. so, in other words, don't use 'game.Players', and use 'workspace' instead of 'game.Workspace', right? RiskoZoSlovenska 239 — 3mo
Ad
Log in to vote
1
Answered by
sleazel 679 Moderation Voter
3 months ago

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.

Log in to vote
0
Answered by 3 months ago

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?

Answer this question