Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 5 years ago
Edited 5 years 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 5 years 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 378 — 5y
Ad
Log in to vote
1
Answered by
sleazel 1287 Moderation Voter
5 years 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 5 years 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