Friday, October 14, 2022
HomeWeb DevelopmentThe right way to add Firebase to your Unity venture

The right way to add Firebase to your Unity venture


Growing video games inside Unity is enjoyable, however in terms of creating the backend system, it’s a ache. It’s because builders have to go away the Unity recreation engine and shift to a completely new growth atmosphere to create a backend database and API endpoints. Mix this with authentication, storage, internet hosting, analytics, and testing infrastructure and you end up in a deep rabbit gap.

To stop this situation, Firebase bundles up all these totally different backend providers in a single place. It’s developed by Google and is straightforward to arrange with Unity.

On this article, you’ll discover ways to create a Firebase Mission, combine it with Unity, and carry out CRUD operations with Firebase.

Unity venture setup

If you happen to haven’t performed so already, create a brand new Unity 3D venture and title it Hi there Firebase.

You are able to do so by launching Unity Hub in your laptop and clicking New venture.

Click New Project

After clicking on New venture, the window beneath pops up. To make sure that we’re making a 3D venture, full the next steps:

  1. Choose 3D from the templates
  2. Replace the Mission Title from My Mission to Hi there Firebase
  3. Click on the Create venture button

Select 3D Then Create Project

The venture will take a couple of minutes to open up in Unity.

Preserve the venture open, and let’s work on configuring Firebase.

The right way to arrange a Firebase Mission within the Firebase Console

Open the Firebase Console in your browser. Click on Add venture.

Add Project

Title the venture HelloFirebaseUnity (as much as you).

Name Project

Preserve Google Analytics disabled. You gained’t want Google Analytics to be taught Firebase. If required, we will all the time add it later to the identical venture from the Firebase Console.

Click on Create venture and wait until it will get created.

Create Project

As soon as the venture is prepared, your venture console will open. Click on on the Unity brand within the venture overview web page.

Unity Icon

Then, enter your package deal title. This may be discovered within the HelloFirebase Unity venture (below File > Construct Settings > Platform > Different Settings > Package deal Title). You may overridde this setting and alter it to something on this format: com.yourcompany.yourprojectname.

Android Package Name

Obtain the google-services.json file and place it within the Belongings folder of your HelloFirebase Unity venture.

Download Google Services Config File

Obtain the Firebase Unity SDK and unzip it anyplace in your native machine.

Contained in the unzipped folder go to firebase_unity_sdk > dotnet4 > double click on FirebaseDatabase.unitypackage. It would open this popup in your Unity venture. Click on Import. If you happen to see any error within the console, merely click on Clear.

Import Files

At this level, you might have accomplished all of the steps required to configure a Firebase venture and register an app, developed in Unity, with Firebase.

In an effort to create a database, go to your venture’s Firebase Console. From the left-hand aspect menu, click on Realtime Database.

Realtime Database

Click on Create Database.

Create Database

Choose the Realtime Database location as United States. Click on Subsequent.


Extra nice articles from LogRocket:


Set Up Database

Choose check mode. Click on Allow.

Start in Test Mode

Please word that it is best to by no means preserve the database in Take a look at Mode throughout manufacturing. It’s extremely unsafe as a result of anybody might make adjustments to your database. If you’re experimenting round or casually doing a little analysis, then Take a look at Mode is totally acceptable.

The right way to construction information in Firebase

Earlier than leaping into the script and code, let’s take a minute to know how Firebase shops information within the Realtime Database.

The Realtime Database is so named as a result of it shops and syncs information in actual time. Which means if information is modified or up to date in a single place, it immediately will get up to date in all related gadgets with out the necessity for making a brand new request from the consumer to the server. Isn’t that nice? All gadgets which have your app sync any up to date information inside milliseconds.

All this information is saved in JSON Format. JSON is an ordinary format for storing and transferring information. This information is in key-value pairs. That is the way it appears to be like:

{
      "customers" : {
            "user_id_1" : {"title": "John Doe", "rating":"100"},  
        "user_id_2" : {"title": "Jane Doe", "rating": "500"}
       }
}

The above information will be learn as follows:

  • John Doe is a person. He has a rating of 100 factors
  • Jane Doe is a person. She has a rating of 500 factors

There are a number of methods to symbolize information. You may have a totally totally different illustration of the identical information that I’ve proven above.

The right way to carry out CRUD Operations in Firebase with Unity

CRUD stands for:

  • Creating
  • Studying
  • Updating
  • Deleting

These are normal operations that may be carried out on all databases both programmatically or manually from the Firebase Console. We are going to check out each the methods beneath.

Let’s discover ways to carry out these operations one after the other.

The right way to create a database in Firebase

Manually

From the Firebase Console > Your Mission > Realtime Database click on on the plus icon.

Plus Icon

Then, add customers as the important thing. Then, click on on the plus icon.

Click Plus Icon

Then add user_id_1 as the important thing and John Doe as the worth. Click on Add. It is a baby of customers. I’ve taken user_id_1 for instance. The user_id_1 ought to ideally be generated programmatically. It may very well be a tool’s distinctive identification quantity or another distinctive string.

Add User ID

This database was created manually, however you can not comply with the identical course of when you might have customers on your personal recreation or app.

Give it some thought: in case your recreation is successful and it has a million customers, will you actually sit and sort away 1,000,000 names and person IDs? After all not!

Due to this fact, let’s see how to do that programmatically.

Programmatically

To create the identical database above programmatically:

Open up your Unity venture.

Create an empty GameObject (proper click on in Hierarchy panel > Create Empty). If you happen to examine the properties within the inspector panel for this GameObject, it gained’t have something in any respect. That’s the reason it’s an empty object.

Create Empty GameObject

Rename the empty GameObject to FirebaseDatabaseManager. Then click on Add Element > New script > title the script as FirebaseDatabaseManager > Create and Add.

Add Component

Double click on to open the FirebaseDatabaseManager.cs script in Visible Studio.

Change every thing with this code (we’ll perceive the logic somewhat later code). It is very important save the file (CTRL + S). In any other case, it gained’t replicate the adjustments that you simply made to the FirebaseDatabaseManager.cs script:

utilizing Firebase.Database;
utilizing System.Collections;
utilizing System.Collections.Generic;
utilizing UnityEngine;

public class FirebaseDatabaseManager : MonoBehaviour
{
    string userId;
    DatabaseReference reference;

    void Begin()
    {
        userId = SystemInfo.deviceUniqueIdentifier;
        reference = FirebaseDatabase.DefaultInstance.RootReference;
        CreateNewUser();
    }

    public void CreateNewUser()
    {
        reference.Baby("customers").Baby(userId).SetValueAsync("John Doe");
        Debug.Log("New Person Created");
    }
}

Soar again to the Unity Editor and click on the Play button after which examine the console. You need to see New Person Created with no error messages.

Now go to the Firebase Console > Your Mission > Realtime Database. You will note a key (your system’s key) with the worth of John Doe created.

User Created

Alright! Let’s perceive the code:

  1. userId shops the system’s (by which the app runs) distinctive identifier code
  2. reference shops the foundation of your Firebase Realtime Database
  3. CreateNewUser() is only a technique name. Inside it,
    • we’re traversing the JSON tree. So we begin from the foundation and create a baby of it referred to as customers. Then we create one other baby referred to as system_user_id and set it’s worth as John Doe
    • Then I added a easy print assertion for debugging functions. A message like this helps the developer perceive that this technique was certainly executed

Nice. You’ll be able to write information to the database.

Your database has the person’s title however not the rating. If you happen to bear in mind, we needed to construction our information like this:

{
      "customers" : {
            "user_id_1" : {"title": "John Doe", "rating":"100"},  
            "user_id_2" : {"title": "Jane Doe", "rating": "500"}
       }
}

So how can we do this? Attempt as soon as after which scroll all the way down to examine the answer.

All now we have to do is to enter the FirebaseDatabaseManager.cs script and add one line to the CreateNewUser() technique:

public void CreateNewUser()
{
        reference.Baby("customers")
            .Baby(userId)
            .Baby("title")
            .SetValueAsync("John Doe");

        reference.Baby("customers")
            .Baby(userId)
            .Baby("rating")
            .SetValueAsync(100);

        Debug.Log("New Person Created");
}

Hit the play button and return to your Firebase Console. If all went effectively, that is what you will note:

User ID Name Score

Superior! We used a C# script in Unity to create information within the Firebase Realtime Database.

The right way to learn the database

Go to your FirebaseDatabaseManager.cs script.

Remark out CreateNewUser() as we don’t must name it anymore.

Create one other technique ReadDatabase() and name it within the Begin technique like this:

 void Begin()
    {
        userId = SystemInfo.deviceUniqueIdentifier;
        reference = FirebaseDatabase.DefaultInstance.RootReference;
        // CreateNewUser();
        ReadDatabase();
    }


public void ReadDatabase()
    {
        reference.Baby("customers")
                 .Baby(userId)
                 .Baby("title")
                 .GetValueAsync().ContinueWithOnMainThread(activity => {
                    if (activity.IsFaulted)
                        {
                             Debug.Log(activity.Exception.Message);
                        }
                        else if (activity.IsCompleted)
                        {
                            DataSnapshot snapshot = activity.End result;
                            Debug.Log("Title=" + snapshot.Worth);
                        }
                   });
    }

Return to Unity Editor. Hit the play button. You will note Title=John Doe message printed within the console.

Within the code above, DataSnapshot is a snapshot of the key-value pairs or baby information on the path that you simply select to traverse within the JSON tree. If there is no such thing as a information, you get null.

The right way to replace the database

Updating the database merely means:

  1. if there’s a matching report within the database already, then its worth ought to be modified
  2. If there is no such thing as a matching report within the database, then the situation is similar as making a database that we noticed earlier

You may attempt the identical code within the The right way to create a database in Firebase part. Simply substitute John Doe with your personal title. It would mechanically discover a baby together with your system ID and replace the worth for that key.

The right way to delete the database

Go to your FirebaseDatabaseManager.cs script.

Remark out CreateNewUser() as we don’t must name it anymore.

Create one other technique RemoveUserWithUserID() and name it within the Begin technique like this:

void Begin()
{
        userId = SystemInfo.deviceUniqueIdentifier;
        reference = FirebaseDatabase.DefaultInstance.RootReference;
        // CreateNewUser();

        RemoveUserWithUserID();
}

public void RemoveUserWithUserID()
{
        reference.Baby("customers")
            .Baby(userId)
            .RemoveValueAsync(); 

        Debug.Log("Person eliminated");
}

Return to Unity Editor. Hit the play button. You will note the Person eliminated message printed within the console.

Then go to your FirebaseConsole. You will note that the kid together with your system ID has been efficiently faraway from the database.

Conclusion

Superior! You simply created a C# script in Unity to speak together with your Firebase Realtime Database. Be happy to discover the opposite superb options of Firebase.

If you happen to face any points or want some assist, please ping me on Twitter or LinkedIn, and take a look at my Gumroad web page or YouTube channel for those who’re on the lookout for extra 3D or AR/VR associated assets.

: Full visibility into your net and cell apps

LogRocket is a frontend software monitoring answer that allows you to replay issues as in the event that they occurred in your personal browser. As an alternative of guessing why errors occur, or asking customers for screenshots and log dumps, LogRocket helps you to replay the session to shortly perceive what went fallacious. It really works completely with any app, no matter framework, and has plugins to log further context from Redux, Vuex, and @ngrx/retailer.

Along with logging Redux actions and state, LogRocket information console logs, JavaScript errors, stacktraces, community requests/responses with headers + our bodies, browser metadata, and customized logs. It additionally devices the DOM to report the HTML and CSS on the web page, recreating pixel-perfect movies of even essentially the most advanced single-page and cell apps.

.



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments