Use of :GetService()?

This is a pretty simple question not too much detail.

Whats the advantages and disadvangrages of using:
game:GetService(“”)
vs
just game._________

What does it do differently and should I use :GetService() when ever I’m getting the core game pieces?

28 Likes

Always use game:GetService(). It’s both possible for developers/scripts to change the names of services, and that a service wont yet be loaded.

I personally change the names of ReplicatedStorage and ServerStorage because the full-names of scripts can be cut-off if they’re too long.

53 Likes

Along with what @Tomarty said, GetService will also create the service if it’s not currently there.

For instance, game:GetService("Teams") will create the Teams service if it’s not currently there. I don’t know if there are other services like that though–but maybe?

So it’s just a safer method for getting services.

16 Likes

Adding on, a lot of services don’t even have their name to the service name by default, so you’ll be inconsistent across services.

3 Likes

I had a talk earlier with one of my friends about this. They said quote “services are promised to be loaded implicitly”. Also, FindService exists too, which is like FindFirstChildOfClass but errors if the class isn’t a service.

2 Likes

Second question cause I didn’t want to spam the forum with posts

You use :WaitForChild() when you don’t expect the object to be there already, such as when you clone?

Not if you don’t use :GetService they’re not. :GetService creates the service if it doesn’t exist.

2 Likes

Second question cause I didn’t want to spam the forum with posts

You use :WaitForChild() when you don’t expect the object to be there already, such as when you clone?

1 Like

No because if you are cloning an object, you will already have a reference to said object. The real reason for :WaitForChild() is that sometimes the script will execute before the object loads in and cause your script to error.

5 Likes

What service, other than teams, “doesn’t exist” and needs to be created? From what I know, they’re all in the DataModel at run time. Those who need teams create it in Studio via the command bar. So essentially what I said isn’t necessarily wrong.

1 Like

TestService is one that comes to mind.

1 Like

WaitForChild is primarily used for client-side code to assure the objects being accessed have loaded/replicated. Such as UI objects.

Not necessary when cloning. When you clone, it’s guaranteed to give you the whole object.

Caveat: Don’t clone an object that might not have fully loaded yet!

12 Likes

Is it okay to use GetService() multiple times on a single machine? For instance, calling the method on several local module scripts

Yes. This is perfectly fine (just dont use it a LOT LOT (never a good practice))

1 Like