Can you use game:GetService() in a LocalScript? Or can you only use it in a server script since it creates the service if it doesn’t exist?
You can use it in a local script. It creates said service if it’s not there. it is also a better way to code.
local ReplicatedStorage = game.ReplicatedStorage
--is the same as
local ReplicatedStorage = game:GetService("ReplicatedStorage")
I know you’re right, but why is it a better way to code?
You can use game:GetService
in both server and client. The reason :GetService
is commonly used is because of race condition.
If you try to directly index a service (e.g. game.TweenService
), we do not know if that service is already created. If it wasn’t then the code would error and stop.
Another method is game:FindService
which is similar to Instance:FindFirstChild
. This basically finds a service and returns it, if the service is not yet created, it will return nil.
Now, game:GetService
, this function finds the service then returns, if none is found it will create it.
A service might not have been created yet when getting it, so creating one would be better.
Yes, server can’t find LocalPlayer and LocalScript can’t find server script and server storage.
But LocalScript can find LocalPlayer.
:GetService()
is actually slower than just indexing a service by a few milliseconds. But it can be beneficial in open-source projects because for example if you do game["Run Service"]
, RunService may not already be created, making it better to use game:GetService("RunService")
or if game:FindService("RunService") == nil then
I don’t believe this is correct. GetService
returns the service whether it’s named correctly or not. For example, if you rename ServerStorage to Stuff, GetService(“ServerStorage”)
will still return ServerStorage. Services load before scripts run.
I never said anything about service instances being renamed.
I never said scripts actually load before services, I only said it might. Tbh, I’m 90% sure that services do load before scripts (other than local scripts on ReplicatedFirst probably), although I still go with the best practice.
The scripts are in the services. The parent always loads before the child.