> For the complete documentation index, see [llms.txt](https://bizachi-dev.gitbook.io/bullethell-elemental-template/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://bizachi-dev.gitbook.io/bullethell-elemental-template/getting-started/quickstart.md).

# Firebase Backend

Accounts with Firebase Authentication and cloud save with Cloud Firestore and the Realtime Database, without writing server code.

With the Firebase backend the template has accounts (email/password and guest), cloud save, friends, guilds, online status and co-op invites, without running your own server.

**Follow every step of this page, in order.** None of them is optional: a missing step is the most common reason for "Firebase does not work". Read the [Offline Backend](/bullethell-elemental-template/getting-started/offline-backend.md) page first; the Unity project setup is the same.

{% hint style="warning" %}
The Firebase Unity SDK does not support WebGL. For browser builds use the Offline or the WebSocket + SQL backend.
{% endhint %}

***

### Checklist

| #  | Where            | Step                                                           |
| -- | ---------------- | -------------------------------------------------------------- |
| 1  | Unity            | Package Name                                                   |
| 2  | Unity            | Import the Firebase SDK (Auth, Firestore, Database)            |
| 3  | Unity            | Add the `FIREBASE` define on every platform                    |
| 4  | Firebase console | Create the project and register the app                        |
| 5  | Unity            | Put `google-services.json` in `Assets/StreamingAssets`         |
| 6  | Firebase console | Enable Email/Password and Anonymous sign-in                    |
| 7  | Firebase console | Create the Firestore database and publish `firestore.rules`    |
| 8  | Firebase console | Create the Realtime Database and publish `database.rules.json` |
| 9  | Firebase console | Create the document `BattlePass/SeasonInfo`                    |
| 10 | Unity            | Select the Firebase backend and create your first account      |
| 11 | Firebase console | Create the document `Admin/Admin` with your UID                |
| 12 | Unity            | Test                                                           |

***

### 1. Package Name

In Unity open **Edit > Project Settings > Player > Other Settings > Identification** and set the **Package Name** (for example `com.yourstudio.yourgame`). You will type exactly the same name in the Firebase console.

<figure><img src="https://215355839-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fc8AVbPtcUOjcVrQx9Eyu%2Fuploads%2FsThaxv1NJXPe363JWqOV%2FApp.png?alt=media&amp;token=5e59cc19-4d56-4b7c-954e-db21f6a0d2d0" alt="Package name in Player Settings"><figcaption><p>The Package Name must match the one registered in Firebase.</p></figcaption></figure>

### 2. Import the Firebase SDK

1. Open the [Firebase Unity SDK archive](https://developers.google.com/unity/archive) and download the `.unitypackage` of these three modules (the template is tested with version **12.10.1**; use the same version for the three):
   * **Firebase Authentication** (`FirebaseAuth.unitypackage`)
   * **Cloud Firestore** (`FirebaseFirestore.unitypackage`)
   * **Firebase Realtime Database** (`FirebaseDatabase.unitypackage`)
2. In Unity, import each one with **Assets > Import Package > Custom Package**.
3. When the External Dependency Manager asks to enable Android auto-resolution, click **Enable**.

<figure><img src="https://215355839-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fc8AVbPtcUOjcVrQx9Eyu%2Fuploads%2F0HOZ4kkmWovLP0YkguoR%2F8.png?alt=media&amp;token=2f97a044-f3a5-4c31-8f69-29397f80449f" alt="Firebase Unity SDK archive"><figcaption><p>Download the .unitypackage of each module.</p></figcaption></figure>

### 3. Add the FIREBASE define

All the Firebase code of the template is inside `#if FIREBASE`. Without the define, the Firebase backend does not exist in the build.

1. Open **Edit > Project Settings > Player > Other Settings > Script Compilation > Scripting Define Symbols**.
2. Click **+**, type `FIREBASE` and click **Apply**.
3. Repeat it on **each platform tab** you build for (Windows/Mac, Android, iOS). The define is saved per platform.
4. Wait for Unity to finish compiling. The console must have no errors.

### 4. Create the Firebase project and register the app

1. Open the [Firebase console](https://console.firebase.google.com/) and click **Create a project** (or **Add project**). Give it a name and finish the wizard.
2. On the project page, click the **Android** icon to add an Android app. In **Android package name** type the Package Name of step 1. Click **Register app**.
3. If you also build for iOS, add an **Apple** app with the same identifier as **Bundle ID**.

<figure><img src="https://215355839-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fc8AVbPtcUOjcVrQx9Eyu%2Fuploads%2FVkhvH1OFITHnCuIOxa2O%2F17.png?alt=media&amp;token=e6697665-a408-49f5-a0bc-91eaad880dec" alt="Register app in Firebase"><figcaption><p>Registering the Android app.</p></figcaption></figure>

{% hint style="info" %}
Register the Android app even if you only build for Windows or Mac: the Editor and desktop builds use its `google-services.json` too.
{% endhint %}

### 5. Put the config file in the project

1. Download `google-services.json` (Android) and, for iOS, `GoogleService-Info.plist`.
2. In Unity, create the folder `Assets/StreamingAssets` if it does not exist.
3. Copy the files into `Assets/StreamingAssets`. Keep the exact file names: a file saved as `google-services (1).json` is not found.

You can skip the remaining pages of the Firebase registration wizard (the SDK is already in the project).

### 6. Enable sign-in

1. In the console open **Build > Authentication** and click **Get started**.
2. Open the **Sign-in method** tab.
3. Enable **Email/Password** (only the first switch) and click **Save**.
4. Click **Add new provider**, choose **Anonymous**, enable it and click **Save**. It is used by the **Play as Guest** button.

<figure><img src="https://215355839-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fc8AVbPtcUOjcVrQx9Eyu%2Fuploads%2FpWXKMFiejX5czMulgq3i%2FAuth.png?alt=media&amp;token=a5a6fa05-717e-4c57-80a8-b728247bd091" alt="Sign-in providers"><figcaption></figcaption></figure>

The password rules of the create account form (minimum and maximum length, uppercase, numbers...) are set in **Game Instance > Authentication Settings** in Unity.

### 7. Create Cloud Firestore and publish its rules

1. Open **Build > Firestore Database** and click **Create database**.
2. Choose a **location** close to your players. It cannot be changed later.
3. Choose **Start in production mode** and click **Create**.
4. Open the **Rules** tab. Delete everything in the editor.
5. In Unity, open `Assets/BulletHellTemplate/Core/DataHandler/Backend/FirebaseRules/firestore.rules` with any text editor, copy the whole file and paste it in the console.
6. Click **Publish**.

{% hint style="warning" %}
The rules of the template are required. With the default production rules every read and write is refused, and the login fails.
{% endhint %}

No Firestore index needs to be created.

### 8. Create the Realtime Database and publish its rules

The Realtime Database keeps the online status of players, the co-op invites and the friends online list.

1. Open **Build > Realtime Database** and click **Create Database**.
2. Choose a location and **Start in locked mode**. Click **Enable**.
3. Open the **Rules** tab. Delete everything.
4. Copy the whole content of `database.rules.json` (same folder as `firestore.rules`) and paste it. Click **Publish**.
5. **Download `google-services.json` again** (Project settings > Your apps) and replace the file in `Assets/StreamingAssets`. The file downloaded before the Realtime Database existed does not contain its address.

<figure><img src="https://215355839-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fc8AVbPtcUOjcVrQx9Eyu%2Fuploads%2FX6DhNMg0Xr6VKI3UJraY%2FpreviewRealtime.png?alt=media&amp;token=bf4e05fd-69ee-4985-bd44-ccd80dcfa92d" alt="Realtime Database"><figcaption></figcaption></figure>

### 9. Create the battle pass season (BattlePass / SeasonInfo)

The battle pass reads its season from this document. Without it the season restarts every time the player logs in and never ends.

In **Firestore Database > Data**:

1. Click **+ Start collection**.
2. **Collection ID**: `BattlePass`. Click **Next**.
3. **Document ID**: type `SeasonInfo` (do not use Auto-ID).
4. Fill the fields. For each extra field click **Add field**:

| Field          | Type      | Value                                                           |
| -------------- | --------- | --------------------------------------------------------------- |
| `Season`       | number    | `1`                                                             |
| `StartSeason`  | timestamp | The date and time the season starts, for example today at 00:00 |
| `DurationDays` | number    | `30` (length of the season in days)                             |

5. Click **Save**.

The field names must be written exactly like this, with the same upper and lower case.

<figure><img src="https://215355839-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fc8AVbPtcUOjcVrQx9Eyu%2Fuploads%2Ff4aP1cD8x0CYXXEdNe6Z%2FConfigDatabase.png?alt=media&amp;token=75eea232-d80c-4166-b8ad-f8cdd8dc84f0" alt="BattlePass SeasonInfo document"><figcaption><p>The SeasonInfo document inside the BattlePass collection.</p></figcaption></figure>

### 10. Select Firebase and create your first account

1. In Unity open the **Login** scene, select **BackendBootstrap** and click the Backend Settings asset in its **Settings** field.
2. Set **Option** to **Firebase**.
3. Press **Play**, open the create account form and create an account with your email and a password.
4. The Home scene opens. Stop Play Mode.
5. In the console open **Authentication > Users**. Your account is listed there. Copy its **User UID** (the long code in the last column).

In **Firestore Database > Data** you can now see the collections created by the template, such as `Players` with a document for your account.

### 11. Create the admin list (Admin / Admin)

This document lists the accounts allowed to use the GM panel in Home (send mail to players, global messages, map events, ban and unban). The template reads it at every login, so create it even if you have no support team yet.

In **Firestore Database > Data**:

1. Click **+ Start collection**.
2. **Collection ID**: `Admin`. Click **Next**.
3. **Document ID**: type `Admin`.
4. Field `gm`, Type **array**. In the first element set the type **string** and paste the **User UID** you copied in step 10.
5. Click **Add field**. Field `support`, Type **array**. Leave its first element as a **string** with an empty value if you have no support accounts yet.
6. Click **Save**.

<figure><img src="https://215355839-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fc8AVbPtcUOjcVrQx9Eyu%2Fuploads%2FfMpPoGe3sfKlCuNqm60N%2FpreviewFirestore.png?alt=media&amp;token=55663b68-a271-47b8-a281-b64bcaf587e1" alt="Admin document with gm and support"><figcaption><p>Admin / Admin with the gm and support lists.</p></figcaption></figure>

To add another GM or support account later, open the document, click the array and add a new **string** element with that account's UID. On Firebase both lists have the same rights.

### 12. Test

Press Play from the Login scene and check:

* The login works with your account and with **Play as Guest**.
* The Battle Pass screen shows **Season 1** and the time left.
* The **ADM Panel** button appears in Home for your account (the GM account).
* A new player appears in **Authentication > Users** and in the `Players` collection.

***

### Do not create these by hand

The template creates the following documents by itself. Creating them by hand, with other field names or types, makes the rules refuse the game's writes:

* `Players` and everything inside it (created at the first login of each player)
* `PlayerNames` (reserved nicknames)
* `Meta/UserCounters` (the numeric player id, the first one is 1000)
* `Friendships`, `Guilds`, `GuildNames`
* `Admin/Mailbox`, `Admin/Events`, `Admin/GlobalMessage` (created by the GM panel the first time it is used)

***

### Battle pass seasons on Firebase

To start a new season, edit `BattlePass/SeasonInfo`: increase `Season` and set a new `StartSeason`. The players see the new season and time left at their next login. On Firebase the pass level and the rewards already claimed are **not** reset automatically when the season changes.

### What the rules protect

There are no Cloud Functions, so the client writes its own data. The rules make sure a player can only change their own account, that GM and support accounts can only change the ban fields of other players, and that shared documents (friendships, guilds, names, the player id counter) only accept the changes the template makes. Balances and progress inside a player's own account are still decided by the client. If you need server-side validation, use the [WebSocket + SQL backend](/bullethell-elemental-template/getting-started/websocketsql-backend-v1.5.md).

In-app purchases are recorded in the player's account, but their receipts are not validated on Firebase.

{% hint style="info" %}
**Paid addons.** The **Loot Box** and **Lucky Wheel** addons (sold separately on the Asset Store) work on Firebase with no extra setup. The **Realtime Global Chat** addon (sold separately) uses the same Realtime Database; its rules are already in `database.rules.json`.
{% endhint %}

***

### Common issues

| Problem                                            | Cause and fix                                                                                                                                              |
| -------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| The login screen never finishes or the login fails | The `FIREBASE` define is missing on the current platform, the SDK packages were not imported, or the rules of step 7 were not published.                   |
| `google-services.json` not found                   | The file is not in `Assets/StreamingAssets` or its name was changed.                                                                                       |
| Account creation fails                             | The password breaks the rules of the Game Instance, or Email/Password sign-in is disabled.                                                                 |
| Guest button fails                                 | Anonymous sign-in is disabled.                                                                                                                             |
| `PERMISSION_DENIED` in the console                 | The rules were not published, or a document was created by hand with other field names.                                                                    |
| The battle pass time left restarts at every login  | `BattlePass/SeasonInfo` is missing or its field names are different (step 9).                                                                              |
| The ADM Panel button does not appear               | `Admin/Admin` is missing, the field is not called `gm`, or the UID in it is not the UID of the logged account (step 11).                                   |
| Friends never show as online                       | The Realtime Database was not created, its rules were not published, or `google-services.json` was downloaded before the database existed (step 8).        |
| Android build fails on dependencies                | Run **Assets > External Dependency Manager > Android Resolver > Force Resolve**. See [Common problems](/bullethell-elemental-template/common-problems.md). |
