Reader small image

You're reading from  Build Your Own Metaverse with Unity

Product typeBook
Published inSep 2023
PublisherPackt
ISBN-139781837631735
Edition1st Edition
Tools
Concepts
Right arrow
Author (1)
David Cantón Nadales
David Cantón Nadales
author image
David Cantón Nadales

David Cantón Nadales, software engineer from Seville, Spain, with more than 15 years of experience. He is currently a Technical Leader at Grupo Viajes El Corte Inglés, a leading travel company in Europe. He has done a multitude of projects and video games with Unity, VR/AR with Oculus, Hololens, HTC Vive, DayDream and LeapMotion. He was ambassador of the Samsung community "Samsung Dev Spain", and organizer of "Google Developers Group Sevilla". He led more than 100 projects throughout his career. As a social entrepreneur stands out Grita, a social network that emerged during the confinement of COVID-19 that allowed to talk to other people and help each other psychologically. In 2022 he won the Top Developers Awards organized by Samsung.
Read more about David Cantón Nadales

Right arrow

Understanding the different Firebase services

Firebase is a cloud platform for web and mobile application development that’s owned by Google. It has SDKs for a wide range of platforms and technologies, which help you use it in virtually any environment, whether it is on the web with JavaScript, a desktop application written in .NET, a native mobile app on Android or iOS, and so on. Most importantly, it has a huge community, which makes this suite a great ally in any project.

It was created in 2011 and Google acquired it in 2014. Initially, it was only a real-time database. Due to its success, more and more features were added, which, in part, allows us to group the SDKs of Google products for different purposes, making it easier to use.

What is Firebase for?

Its essential function is to simplify the creation of web applications and mobile, desktop, and even REST API projects and their development, allowing for high productivity or helping to make the work faster, but without sacrificing quality.

Its tools cover practically any technical challenge that a complete application must overcome, considering that its grouping simplifies the management tasks to the same platform. The functionalities of these tools can be divided into four groups:

  • Compilation
  • Launch and monitoring
  • Analytics
  • Participation

It is especially interesting because it helps developers not need to spend so much time on the backend, both in terms of development and maintenance issues.

Firebase functionalities

This chapter will help you understand and love Firebase from these very pages. During the journey of our project, we will be connecting features and functionalities of our metaverse in this suite.

Compilation

The Compilation section is where Firebase includes the most important functions that you will use the most. Services such as user identification, file hosting, and databases can be accessed from here. The following is a more detailed review of the most important services in this section:

  • Authentication: Identifying the users of an app is necessary in most cases if they want to access all its features. Firebase offers an authentication system that allows both registration (via email and password) and access using profiles from other external platforms (such as Facebook, Google, Apple, or Twitter), which is a very convenient alternative for users who are reluctant to complete the process.

Due to this, these types of tasks are simplified. This is also because access is managed from Google servers and greater security and data protection can be achieved. It should be mentioned that Firebase can securely store login data in the cloud, which prevents someone from having to identify themselves every time they open the application.

  • App Check: This offers security techniques that protect your token-based applications.
  • Firestore Database: One of Firebase’s most prominent and essential tools is real-time databases. These are hosted in the cloud, are non-SQL, and store data as JSON. They allow the data and information of the application to be hosted and available in real time, keeping them updated even if the user does not perform any action.

Firebase automatically sends events to applications when data changes, storing the new data on disk. Even if a user is offline, their data is available to everyone else, and the changes that are made are synchronized once the connection is restored.

Nowadays, Firebase maintains two real-time databases – Realtime Database and Firestore Database. The latter is a very powerful evolution of the former and allows you to manage indexes and make and apply more complex filters from the SDK. We will use the latter in our project.

  • Extensions: These are prefabricated actions that facilitate automated tasks on your database, such as sending an email when a new item is created, optimizing a photo when a user uploads it, translating text from a database field, and so on.
  • Storage: Firebase has a storage system where developers can store their application files (and link them with references to a file tree to improve app performance) and synchronize them. Like most Firebase tools, it can be customized through certain rules. This storage is a great aid for handling user files (photos they have uploaded), which can be served more quickly and easily. It also makes downloading file references more secure.
  • Hosting: Firebase also offers a server to host the apps quickly and easily – that is, static and secure hosting. It provides SSL and HTTP2 security certificates automatically and free of charge for each domain. It works by placing them on Firebase’s Content Delivery Network (CDN), a network that receives the uploaded files and delivers the content.
  • Functions: This option allows you to deploy functions hosted in Firebase as a backend. These functions can be of the REST type (GET, PUT, DELETE, and POST) or of Trigger type – that is, they are launched automatically when something happens in the database, such as when a new document is added, a value changes in a specific field, or a document is deleted.

Finally, you can also create schedule functions. These are equivalent to cron tasks and can be programmed to be executed in a time range – for example, every 5 minutes, every 24 hours, and so on.

  • Machine Learning: These are pre-built functions that make it easier for you to perform tasks in mobile applications, such as recognizing text in a photo, detecting a face, and tracking objects using the camera.
  • Remote Config: This allows you to dynamically configure your project based on constants that you generate in the cloud. These constants can be numeric values, text, or even store a whole tree in JSON. This tool is very powerful if you want to dynamize the look and feel of your app without needing to recompile and deploy. For example, in these constants, we can store a discount of our shop, a Boolean variable that decides whether to display a banner or not.

Launch and monitoring

This section is where Firebase groups the services related to quality and analysis. Important services such as monitoring and managing bugs in our software with Crashlytics, obtaining performance metrics with Performance, robotically testing app features, and distributing binaries to testers can be accessed from here. The following is a more detailed review of the most important services in this section:

  • Crashlytics: To maintain and improve the quality of the app, special attention must be paid to bugs, so bug tracking (and also the overall performance of the app) is key to being able to act and fix them. For this reason, Firebase offers crash reporting, which detects and helps solve the app’s problems, obtaining a very detailed error report (with data such as the device or the situation in which the exception occurs) and organizing them as it groups them by similarity and classifies them by severity.
  • Performance: This provides statistics on the load times of a mobile app or website. Here, you can find metrics calls to other REST APIs that occur within your code.
  • Test Lab: The Test Lab allows you to test your app on virtual Android devices based on the parameters you configure. This way, it is much easier to detect possible errors before launching the application.
  • App Distribution: This allows you to distribute an APK or AAB to private testers. This makes it much easier to manage new versions. Firebase automatically sends notifications to users when you upload a new version for testing.

Analytics

Have you met or heard about Google Analytics before? Firebase Analytics is practically the same but oriented to mobile apps. With this service, you can get powerful information about the users of your app.

Analyzing data and results is key to making consistent and informed decisions for your project and associated marketing strategy. With Firebase Analytics, you can monitor various parameters and obtain a variety of metrics from a single dashboard for free. It is compatible with iOS, Android, C++, and Unity and, among other functions, allows you to do the following:

  • Obtain measurements and analysis of the events taking place in the application. You can receive unlimited reports with up to 25 attributes.
  • Check the performance of events, notifications, and advertising campaigns in networks, based on user behavior.
  • Get to know the user with segmented information. For example, you can obtain statistical data on language, access devices, age, gender, location, and so on. Insights on usage and loyalty to the app can also be obtained.

Participation

Participation is where Firebase groups the services related to communication or interaction with other users of our app. Push messaging communication, the creation and consumption of Magic Links with Dynamic Links, and A/B testing are some of the most interesting services that we will find here. Let’s look at these in more detail:

  • A/B testing: This allows you to use Remote Config to measure the success of your project on two different variants.
  • Messaging: This is useful for sending notifications and messages to various users in real time and through various platforms.
  • Dynamic Links: These are smart links, which allow the user to be redirected to specific areas or contents of the application, depending on the objective to be achieved and the personalization given to various parameters of this URL.

Thus, the operation of these links is directed as we want and ensures a pleasant experience for the user on various platforms. They are particularly useful for directing content to certain segments of users, whether they’re current or potential, in which case they may receive a recommendation to install our app.

  • AdMob: This allows you to monetize your mobile apps easily and intuitively; with a few lines of code, you can display banners and ads automatically.

Advantages and disadvantages of using Firebase

You will probably agree with me that this tool has many benefits for developers who use it. We will add below an interesting link with official documentation and examples, ideal to broaden your knowledge of the services mentioned above.

Here is a list of the benefits of Firebase:

  • Highly recommended for applications that need to share data in real time.
  • Its functionalities complement each other very well and can be easily managed from a single panel. Moreover, it is not necessary to use all these options for the application, and you can choose only those that interest you most.
  • They have official SDKs for client applications developed in iOS, Android, JavaScript, C++, and Unity. They also have libraries to integrate into an API for the NodeJS, Java, Python, and GoLang languages. Finally, although they do not have official support, there are libraries for frameworks such as Angular, Ember, Flutter, React, React Native, Rx, and Vue that are recommended on their website.
  • It allows you to send notifications. They are very simple to implement and manage, and they are also extremely useful for maintaining communication with users.
  • Allows monetization – that is, from Firebase itself, advertising can be added to the app, allowing it to be easily monetized.
  • Includes Analytics, which specializes in certain mobile application metrics and is integrated into the Firebase central panel with a very intuitive operation.
  • Google offers abundant introductory and informative documentation (in great depth) to make diving into Firebase much easier.
  • Free email support, regardless of whether the developer uses the free or paid version.
  • It is scalable – that is, the startup is free but allows it to adapt to the needs of the application with different payment plans.
  • Offers security to users with SSL certificates.
  • Allows developers to take their attention away from the backend and complex infrastructures to focus entirely on other aspects.

The most mentioned disadvantage is Firebase’s price. We have already discussed the scalability of Firebase, where starting with the Spark plan is free. However, it has limitations (mainly regarding the number of concurrent users and storage space), so it may be necessary to purchase a paid version. The paid plans are Flame ($25 per month) and Blaze (pay-as-you-go).

As a side note, in the many years that I have been using Firebase, I have deployed more than 50 projects, some small, some medium, and some larger, and I can say that I have received invoices of a few cents or on occasion less than $10. This is an insignificant amount, in my opinion, for the stability, quality, and monitoring of the services offered.

You can always set up budget alerts and decide to stop the service when your budget is exceeded – you will receive an email when you are approaching your limit.

Note

You can find technical documentation and tutorials by browsing to https://firebase.google.com/docs.

At this point, you know what Firebase can offer us. As you have seen, it is a suite full of fascinating services. Can you imagine how all this will help us in our impressive metaverse? From Chapter 3, Preparing Our Home Sweet Home: Part 1, we will perform various actions and integrate our project with Firebase services, step by step and progressively. Now, let’s get down to business and create our project in the Firebase console.

Configuring a new Firebase project

Firebase will be our traveling companion throughout this book. It is like a Swiss Army knife that will provide us with solutions to technical problems, such as data persistence in the cloud, dynamic configuration, hosting user-generated files, identifying users in our system, and much more.

To explore the tools offered by this Google suite, we must create an account for free:

  1. Navigate to https://console.firebase.google.com.
  2. Since Firebase is a Google service, you will need to use your Gmail account to log in. If you are already logged in with Gmail, you will be taken directly to the welcome screen; otherwise, you will be prompted to log in. Once logged in, you will see the following screen:
Figure 1.25 – The welcome page in the Firebase console

Figure 1.25 – The welcome page in the Firebase console

  1. Click on the Create a project button. At this point, we will be asked for the name of the project. We can use the same name we used for our project in Unity:
Figure 1.26 – Setting up the name of your project in Firebase

Figure 1.26 – Setting up the name of your project in Firebase

  1. After you have entered the name of your project, you can click the Continue button.
  2. In step 2 of 3, the wizard will ask you if you want to activate Google Analytics. I recommend enabling the Enable Google Analytics for this project option as it will be very useful in the future.
  3. When you click on Continue, it will ask you the location that your Analytics account will have. Google Analytics will ask you to select an active account or create a new one, if you do not have one, you can select the Create new account option, in this case, after choosing an account name, accept the Google Analytics terms of use and check the Use the default settings to share Google Analytics data box to make the account creation easy and click the Continue button.
  4. Firebase will take a few seconds to finish configuring the project, so be patient. Once the process has finished... congratulations! You have successfully created your first Firebase project:
Figure 1.27 – The home page of the new Firebase project

Figure 1.27 – The home page of the new Firebase project

Great! With that, you know all the theory behind Firebase’s services and created your first project in the console. Now, let’s go one step further and download the Firebase SDK for Unity. This is a very important first step so that in future chapters, where we need to program our scripts to access Firebase, we have done all the necessary work already and we won’t have to stop.

Installing the Firebase SDK

We have reached the last part of this chapter; after this step, we will focus more on practice and less on theory. We have already seen all the benefits that Firebase offers; after this section, you will understand the reason you should use it in our project.

Next, we are going to follow a few simple steps to download and install the Firebase SDK in our project. To do this, execute the following steps:

  1. Navigate to https://firebase.google.com/download/unity.
  2. The Firebase SDK will automatically start downloading. If this does not happen, look for a hyperlink that looks like what’s shown in Figure 1.28:
Figure 1.28 – Manual download button

Figure 1.28 – Manual download button

  1. It may take some time to download as it is approximately 940 MB. In the folder where your downloads land, you will find a ZIP file named firebase_unity_sdk_X.X.X.zip. In my case, I have downloaded the firebase_unity_sdk_10.1.1.zip version.
  2. When unzipping, a new folder called firebase_unity_sdk will appear, the contents of which are shown in Figure 1.29:
Figure 1.29 – Firebase SDK files for Unity

Figure 1.29 – Firebase SDK files for Unity

  1. This is fantastic! As you can see, the SDK comes fragmented by services. This will help us integrate only what we are going to need and expand in the future if we need new functionality that requires it. We will avoid having plugins and unnecessary code in our project.
  2. To get started in the following chapters, we will need to install FirebaseAuth.unitypackage, FirebaseFirestore.unitypackage, and FirebaseStorage.unitypackage. When we need more functionality in our project, we will go back to this folder and install what we need.
  3. Double-click on FirebaseAuth.unitypackage to install it. A modal window will open in Unity, warning us about the import and showing us which files are going to be created. Click on the Import button:
Figure 1.30 – Unity’s new asset import dialog

Figure 1.30 – Unity’s new asset import dialog

  1. When the progress bar finishes, do the same with the FirebaseFirestore.unitypackage and FirebaseStorage.unitypackage files.

Once you’ve finished installing these, you will see that a new folder has been created in your project called Firebase, which contains the internal libraries needed to use it in the code we will program later:

Figure 1.31 – New Firebase folder and configuration warning

Figure 1.31 – New Firebase folder and configuration warning

As you may have seen, a yellow warning about a missing configuration will appear. You might be wondering, Once I have imported the SDK and I have created my project in the Firebase console, how can I connect the Unity project with the Firebase console? This is done with the google-services.json file for Android and the GoogleService-Info.plist file for iOS. For Windows, Mac, and Linux, Firebase will take the google-services.json mobile file and automatically generate one called google-services-desktop.json the first time you run the project after importing the files.

  1. To generate these files, go to the Firebase console at https://console.firebase.google.com.
  2. On the main screen, click on the Unity icon. You can also access it from the gear button and click on the Project settings option:
Figure 1.32 – Preparing Unity’s configuration in the Firebase console

Figure 1.32 – Preparing Unity’s configuration in the Firebase console

  1. You will be presented with a form that contains simple information that you must fill in to continue.
  2. Check the Register as an Apple app check box and enter an Apple Package ID property of your choice. Here, I have entered com.mymetaverse.app (it must be in inverted domain format, which is comprised of three parts – xxx.xxx.xxx).
  3. Check the Register as Android app check box and enter an Android Package Name property. You can use the same one you entered for iOS.
  4. Click on the Register App button.
  5. Once this process has finished, you will be prompted to download the two files that we had previously named. The remaining steps of the wizard do not require further action, so you can click on the Continue button until it is finished:
Figure 1.33 – Downloading the configuration files for the Unity project

Figure 1.33 – Downloading the configuration files for the Unity project

  1. Finally, drag the two files (google-services.json and GoogleService-Info.plist) to the root of your Unity project, just inside the Assets folder:
Figure 1.34 – Adding the configuration files to the Assets folder

Figure 1.34 – Adding the configuration files to the Assets folder

Congratulations! With this last step, we have perfectly configured our project with Firebase. Finally, I would like to warn you about the yellow warning that appeared before. This will not disappear on its own – you have to press the Clear button that is located in the Console panel.

Congratulations! You have finished configuring Firebase and connected it to our project. I know that this part may seem tedious because it is very theoretical and focuses on configuration tasks, but it is tremendously necessary to be able to advance without obstacles in the following chapters.

Having connected the project in the Firebase console to our Unity project, we will be able to start programming functionalities that attack our Firebase database directly, for example. We will be able to integrate a sign-in/sign-up system for our users, make queries to the database, and much more.

Previous PageNext Page
You have been reading a chapter from
Build Your Own Metaverse with Unity
Published in: Sep 2023Publisher: PacktISBN-13: 9781837631735
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
David Cantón Nadales

David Cantón Nadales, software engineer from Seville, Spain, with more than 15 years of experience. He is currently a Technical Leader at Grupo Viajes El Corte Inglés, a leading travel company in Europe. He has done a multitude of projects and video games with Unity, VR/AR with Oculus, Hololens, HTC Vive, DayDream and LeapMotion. He was ambassador of the Samsung community "Samsung Dev Spain", and organizer of "Google Developers Group Sevilla". He led more than 100 projects throughout his career. As a social entrepreneur stands out Grita, a social network that emerged during the confinement of COVID-19 that allowed to talk to other people and help each other psychologically. In 2022 he won the Top Developers Awards organized by Samsung.
Read more about David Cantón Nadales