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 Service
s like TweenService
or DebrisService
, which aren't found in the Explorer.
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.)
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?