[MUSIC PLAYING]
PATRICK MARTIN: Hi, everybody.
My name's Patrick Martin.
And I'll be walking you through setting up Firebase
Authentication in Unity.
In this video, I'll go over the basics
you need to quickly and easily provide your players
with an identity in your game.
From here, you can either use the Firebase Authentication
Admin SDK to run your own custom backend
or use any of Firebase's backend as a service products
to create dynamic living spaces in which your game
and its players can grow.
In this video, I want to show you
how you can authenticate a player using an email address
and password.
This is one of the easiest methods of player
authentication and doesn't require any third-party SDK
to function.
To start, I have this really fun game where I periodically
mine some resource so that I can later craft items with it.
I want to persist player progress into the cloud.
And in order to do that, I'm going
to need to know who this player is.
So let's see how I can get my players some user accounts
and fast.
Before you begin, you should already
have a Firebase project set up and linked to this Unity game.
If this is your first time using Firebase
or you need a brief reminder, the basics
are covered in this video.
There is a link in the description below if you
need to reference it later.
For Firebase authentication, you want
to add the Firebase Auth Unity package from the zip
file you downloaded in the previous video.
Since I'm using .NET 4 in my project,
I'll pull in the package from the similarly named folder.
Next, I want to enable email and password authentication
in the Firebase console.
I'm going to head on over to the Firebase console,
select my project, head on over to the Authentication section,
then select Sign In Methods.
Then I flip the switch here to enable email password sign in.
So back to my Unity project, I have a brief loading screen
whose entire purpose is to call CheckAndFixDependenciesAsync.
Once that completes, I automatically load a main menu.
So let's open that up.
What I want to implement first is this registration scene.
Your users will want you to do a little bit of user experience
work, though, before making this call.
Here, I've made sure that Unity treats the email input
as an email field.
I've also added two password fields
and set their content type to password.
And I created a fast little script
to make sure the user puts something in the email field
and that their passwords match.
Let me hit Play real fast so you can see this in action.
Here, I'm entering my credentials.
And you can see that the game yells
at me because the passwords don't match.
For performing the actual registration,
I have a separate button script.
If I look at this in the inspector,
it takes a registration flow, as well as a registration button
to listen for clicks on.
It also raises events for success and failure.
I don't want to go over the Unity event system in detail
right now.
But if you hit Play, you can see that it's
showing a failure dialog telling me that I
need to implement registration.
There's nothing to do now but abide.
If I start at the top, I have a button and a registered email
flow dependencies.
I try to help out developers using my script
by doing a first pass discovery of these
during my reset callback.
Then in start, I register all of my event handlers
and get to a nice default state.
I use UpdateInteractable to control
when this button is clickable.
That is when the register email flow
has all the necessary information,
and we're not in the process of registering a user.
Finally, I get down into my Event Handler section
where I can focus on a handle button clicked.
I have a coroutine that I start here called Register.
If I look at its implementation, I
see that it just sets the coroutine
to null and recomputes button enabled.
Let's fill this out.
First, I'll grab an instance to the auth.
Next, I'll start the user registration
by calling create user with email and password async,
storing the resulting task.
Now, notice that this is a coroutine.
There are many ways to handle asynchronous calls in Firebase
that I personally prefer this method,
as it slots in very well with the Unity MonoBehaviour
Lifecycle.
Its complete should become true, whether registration
succeeds or fails.
So I'll just wait until that becomes true.
A note here--
Unity will check this condition on the task
every frame between the update and late update
until the task completes.
This is not necessarily the most efficient way
to perform this sort of logic.
But it's certainly the most foolproof.
Now, when that task completes, I'll
first check to see if anything went wrong.
You should perform this check since exceptions
are raised for typical conditions,
like an email address already being registered
or passwords being too short.
Finally, I'll raise a notification
when this succeeds.
Testing this out, I can see that it runs.
I can also jump over to the Firebase console
to see my newly created user.
I can access this user data and a game as well.
Let's create a quick script to act as the player label.
I can easily just call currentUser.UserID to find
the ID of the user.
This is a unique ID that is associated
with every user who signs in with Firebase Auth
no matter how they sign in.
I can also call currentUser.Email to show
the email address.
Another cool fact-- if you use any other Firebase Unity
plugin that's aware of user accounts,
the token for this user session is automatically sent along.
For example, if you have access rules around the Firebase
database, these are now automatically applied
without any additional work on your part.
I won't cover access rules here.
But there are some awesome resources on that subject,
including this awesome I/O talk from 2016.
You may have noticed that I appear
to remain logged in between runs of the Unity Editor.
This isn't some fancy movie magic.
Like most of the Firebase client SDKs,
Firebase authentication does much more than just wrap REST
calls for you.
In the case of authentication, we'll
actually cache your user information
and securely persist it between runs of your app.
For this app, this means that I can write a quick script that
just checks to see if a player is logged
in so they don't have to type their password every time
a game starts.
This is an excellent user experience
win that I just get for free.
To see how this works, I'll switch back to my main menu
scene and write a quick script to load a scene when
the user is logged in.
So first, I take a scene to load is a serialized field.
Then I register for the auth state changed event
passing it a function named the HandleAuthStateChanged.
This function simply calls CheckUser.
I'll also jump back up and execute CheckUser right
after registration.
I can't forget to unregister this event in OnDestroy.
Finally, the meat of this MonoBehaviour is in CheckUser.
I just check if the current user is not null.
Then I ask Unity Scene Manager to load sceneToLoad.
If I add this to my main menu scene,
I can make it load the game if I'm already signed in.
Lets hit Play to see how this works.
By changing the conditional to CurrentUser equals to null,
I can instead load a scene when the user is logged out.
If I go over into the game scene,
you can see this LoadSceneWhenUserLoggedOut
script.
I will demonstrate this working.
But first, I need to log a player out.
To do this, I have this Logout button and a placeholder
script.
Logging out is probably one of the simplest Firebase functions
you can call.
It's synchronous, so you don't have to yield or await
any task, and has no return value,
so there's not much to handle after calling it.
Here, I'll make the Logout button just
implement IPointerClickHandler so it automatically
receives an OnPointerClick event if attached
to something like a button.
Then I'll just call DefaultInstance SignOut.
That's it.
Let's test this out.
Note that your user credentials are persisted even
in the editor.
So when I hit Play, I'm already logged in.
And now I can click Logout to get back to the main menu.
Now, for the last thing I need--
a login scene so that a user who already has an account
can sign in.
I've already thrown something together.
So let me open that up.
If I press Play now, I can see that it looks just
like the registration scene.
I can inspect the Login button and see
that there's a Login button script just
like the Registration button.
It takes a button but also an email and password field
directly since there isn't complicated UI state management
here.
I also see that it has a success and failure callback.
And if I press Login now, I get an error just
like registration asking me to implement it.
So just like the Registration button,
I have everything filled out except the login logic.
I start by calling SignInWithEmailAndPasswordAsync.
Then I save the task that returns.
Then I wait until that task completes.
Finally, I notify any listeners and clear the loginCoroutine
and call it a day.
For a run this in the editor, it works just as expected.
I can login as the user I just created.
I built this all out in the Unity Editor.
And the editor support is one of my favorite features
of the Firebase plugin.
Given this, don't forget to run your game on your phone
once you've gotten everything else working.
It's easy to build a UI that won't scale down well.
With all that, you should be ready to authenticate
your users.
So where do we go from here?
You should start looking into any authentication providers
that your users may expect in your app.
One I love is Anonymous Authentication,
which lets you login a single installation of your game
rather than some user account.
So you can just postpone the user account creation process
without restricting your connected features.
You can also integrate login buttons
for common social networks, as well as
play games on Android and Game Center on iOS.
Now would also be a great time to investigate
Firebase Realtime Database, Firebase Cloud Storage,
or Firebase Cloud Functions, as all of these products
integrate seamlessly with Firebase Authentication.
Let me know what you build using Firebase Authentication,
or what you want me to cover next time either
in the comments below or @puxOr on the Twitter.
Until next time, stay awesome.
[MUSIC PLAYING]