This is the 2nd part of the series of tutorial. If you have not setup the Firebase SDK and want to know how to create and manage project in Firebase Console, refer to my previous post below:
Using Firebase in Unity3D Tutorial 1: Basics and setup
In this article, I am going to focus on using Firebase to support user authorization or user login features. Simple user name and password based authorization is demonstrated.
Source Code hosted at GitHub here.
(Open Assets\EmailPassword.Unity and run on your android device!)
- It is assumed that you have already created or imported a Firebase project in Firebase Console
- Go to the Firebase Console and click the project you are going to work with.
- Then click the “Authorization” link from the left navigation menu
- Click “SET UP SIGN_IN METHOD” button, then click the edit button on “Email/Password” item
- Enable this option and save the settings.
- You can customize the email template for the authorization, but this is beyond the scope this article.
- In Unity3D, add a new scene and name it “EmailPassword”
- Add a script “EmailPassword.cs”, attach it to the camera or other game object
- Add below code snippet (Copy all code here):
void Start() { auth = FirebaseAuth.DefaultInstance; //Just an example to save typing in the login form UserNameInput.text = "demofirebase@gmail.com"; PasswordInput.text = "abcdefgh"; SignupButton.onClick.AddListener(() => Signup(UserNameInput.text, PasswordInput.text)); LoginButton.onClick.AddListener(() => Login(UserNameInput.text, PasswordInput.text)); }
public void Signup(string email, string password) { if (string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password)) { //Error handling return; } auth.CreateUserWithEmailAndPasswordAsync(email, password).ContinueWith(task => { if (task.IsCanceled) { Debug.LogError("CreateUserWithEmailAndPasswordAsync was canceled."); return; } if (task.IsFaulted) { Debug.LogError("CreateUserWithEmailAndPasswordAsync error: " + task.Exception); if(task.Exception.InnerExceptions.Count >0) UpdateErrorMessage(task.Exception.InnerExceptions[0].Message); return; } FirebaseUser newUser = task.Result; // Firebase user has been created. Debug.LogFormat("Firebase user created successfully: {0} ({1})", newUser.DisplayName, newUser.UserId); UpdateErrorMessage("Signup Success"); }); }
public void Login(string email, string password) { auth.SignInWithEmailAndPasswordAsync(email, password).ContinueWith(task => { if (task.IsCanceled) { Debug.LogError("SignInWithEmailAndPasswordAsync canceled."); return; } if (task.IsFaulted) { Debug.LogError("SignInWithEmailAndPasswordAsync error: " + task.Exception); if (task.Exception.InnerExceptions.Count > 0) UpdateErrorMessage(task.Exception.InnerExceptions[0].Message); return; } FirebaseUser user = task.Result; Debug.LogFormat("User signed in successfully: {0} ({1})", user.DisplayName, user.UserId); SceneManager.LoadScene("LoginResults"); }); }
I also created another scene called “LoginResults”, which has only a label to show if the login is successful, and the scene is loaded when login succeeds.
- Now run the app ON YOUR DEVICE! You will see the both the user creation and login succeed!
- There is a post on Stackoverflow, mentioning that he cannot use firebase SDK to create user with email and password, there are possible several reasons:
- The app was run in the Editor, rather than on the device
- The configuration file is not updated after you add Firebase Auth feature
- The password is shorter than 6 chacters
- The email address is in invalid form, e.g. abcdef@aaa
After taking care of all above measures, your Unity3D app should run well on your device now!
One of the unresolved issues for email/password based authorization is that we did not force Email Verification. To enforce this, use below code in Login():
- First we try to sign in the user with given email and password;
- And then check if the user’s email is verified;
- if not, we will sign out the user until it is verified.
But how do we send the verification email? You can do this at the end of the Signup process programmatically:
You will get the verification email then:
Done!
Source Code hosted at GitHub here. (Note: You might need to substitute the configuration file, bundle ID etc. with your own one got from Firebase Console.)
Happy coding!
Pingback: Using Firebase in Unity3D Tutorial 1: Basics and setup | Xinyustudio
Hi. Will there be another tutorial “Using Firebase in Unity3D: Facebook Authorization” or may be there is a link to an example?
Sorry for my bad English.
And this tutorials is good. Thanks.
Hey, nice tutorial.
I’ve been having this problem for some time. Every time I let the user log out and try to let it connect again, the application freezes and crash. Any idea what could be happening?
Keep getting NullReferenceNotSetToAnObject
Hello, do you know how to save the user.DisplayName? I want that the user can be able to login and then that I have access to his name.Display. For exemplo: i logged in with ju@gmail.com, but I want that the display name appears “Juliany”. How can i do that?
Where is the UpdateTaskStatusMessage(task, “SendEmailVerificationAsync”) method coming from or what it the method i can not find it and am getting errors
Hello, do you know how to save the user.DisplayName? I want that the user can be able to login and then that I have access to his name.Display. For exemplo: i logged in with ju@gmail.com, but I want that the display name appears “Juliany”. How can i do that? i have a same query?
.Thank for this code. But there is a problem.
If an email address is saved, only debug.log say to our.
If you want to change any object in task.IsFaulted stuation you dont.
For example:
….
if(task.IsFaulted)
{
…..
MessageText.Text = “This email is used!!!”;
return;
}
….
Because this task dont finished yet.
What we can this stuation?