Hello developers! so i was watching AlvinBlox’s video about GetService() and Services i didn’t understand really well. Can anyone explain what and how it works? . Am sorry if i judge on someone. Thank you.
It’s basically a way to get a service it’s self explanatory. For this example I am gonna be using User Input Service.
-- We are gonna get the service. So we can use it.
local UserInputService = game:GetService("UserInputService")
--[[ After we have defined the service we can use any of its properties.
I am gonna use a sample function of the User Input Service. ]]--
local function onInputBegan(input, gameProcessed)
if input.UserInputType == Enum.UserInputType.MouseButton1 then
print("The left mouse button has been pressed!")
end
end
UserInputService.InputBegan:Connect(onInputBegan)
Thank you so much i really appreciate that! Thank you!
And in some cases the services you see in your explorer you could say
game.Workspace
game.Players
Services contain functions and properties created by Roblox, such as the :GetPlayers() function of Players which will return a table of all players currently in the game.
Some services are automatically added to the game, such as Workspace, Players, etc.
Others, however, need to be inserted using game:GetService().
Another benefit of using GetService is that RunService is named ‘Run Service’ under the DataModel (no clue why) however GetService allows you to use RunService here. Without GetService you’d be required to use game["Run Service"]
which is seriously uncanonical.
Using get service in scripts is a better practice, it is more secure because if an exploiter renamed workspace, then your scripts might fail. So use
game:GetService(“”) instead of
game.Service
It is worth mentioning GetService() will create the service you are trying to access if it doesn’t currently exist. With teams service developers have to insert it, so using GetService("Teams")
will create the Teams Service if it isn’t currently there.
GetService() is the best option for this. GetService creates the service if it hasn’t been created yet upon calling it, and it also returns the classname instead of its actual name, which is good if you renamed your services in the game.
As oppose to game.Workspace
or workspace
, you would write:
local workspace = game:GetService("Workspace")
Same with players,
local plr = game:GetService("Players")
So on and so forth…