Get Started with Firebase Realtime Database for Unity

The Firebase Realtime Database stores and synchronizes data with our NoSQL cloud database. Data is synced across all clients in realtime, and remains available when your app goes offline.

Before you begin

Before you can use the Firebase Realtime Database, you will need to create a Firebase project, and add the Firebase Unity SDK packages to your Unity project.

Setup:

Prerequisites

Android

iOS

  • Unity 5.0 or later
  • Xcode 8.0 or later

If you don't have a Unity project already, you can download one of our quickstart samples and experiment with a specific Firebase feature. If you're using a quickstart, remember to get the bundle identifier from the project settings; you need it for the next step.

Set up your app in the Firebase console

To add Firebase to your app, you need a Firebase project and a Firebase configuration file for your app.

To create a Firebase project:

  1. Go to the Firebase console.

  2. Click Add project, then select or enter a Project name.

    • If you have an existing Google project associated with your app, select the project from the Project name dropdown menu.
    • If you don't have an existing Google project, enter a new Project name.
  3. (Optional) Edit the Project ID.

    Firebase automatically assigns a unique ID to your Firebase project. This identifier displays in publicly visible Firebase services, for example:

    • Default database URL — your-project-id.firebaseio.com
    • Default hosting subdomain — your-project-id.firebaseapp.com
  4. Follow the remaining setup steps, then click Create project (or Add Firebase, if you're using an existing Google project).

Firebase automatically provisions resources for your Firebase project. The process typically takes a few minutes. When the process completes, you'll be taken to the overview page for your Firebase project in the Firebase console.

Android

  1. Click Add Firebase to your Android app and follow the setup steps. If you're importing an existing Google project, this may happen automatically and you can just download the config file.
  2. When prompted, enter your app's package name. It's important to enter the package name your app is using; this can only be set when you add an app to your Firebase project.
  3. During the process, you'll download a google-services.json file. You can download this file again at any time.
  4. After you add the initialization code, run your app to send verification to the Firebase console that you've successfully installed Firebase.

iOS

  1. Click Add Firebase to your iOS app and follow the setup steps. If you're importing an existing Google project, this may happen automatically and you can just download the config file.
  2. When prompted, enter your app's bundle ID. It's important to enter the bundle ID your app is using; this can only be set when you add an app to your Firebase project.
  3. During the process, you'll download a GoogleService-Info.plist file. You can download this file again at any time.
  4. After you add the initialization code, run your app to send verification to the Firebase console that you've successfully installed Firebase.
  5. Drag the GoogleService-Info.plist downloaded from the Firebase console into any folder in the Unity project.

Add the Firebase Unity SDK to your app

  1. Download the Firebase Unity SDK.
  2. Select the Assets > Import Package > Custom Package menu item.
  3. Import FirebaseDatabase.unitypackage from the directory that matches the version of Unity you use:
    • Unity 5.x and earlier use the .NET 3.x framework, so you need to import the dotnet3/FirebaseDatabase.unitypackage package.
    • Unity 2017.x and newer allow the use of the .NET 4.x framework. If your project is configured to use .NET 4.x, import the dotnet4/FirebaseDatabase.unitypackage package.
  4. When the Import Unity Package window appears, click the Import button.

Initialize the SDK

The Firebase Unity SDK on Android requires Google Play services, which must be up-to-date before the SDK can be used. The following code should be added at the start of your application to check for and optionally update Google Play services to the version required by the Firebase Unity SDK before calling any other methods in the SDK.

Firebase.FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task => {
  var dependencyStatus = task.Result;
  if (dependencyStatus == Firebase.DependencyStatus.Available) {
    // Create and hold a reference to your FirebaseApp, i.e.
    //   app = Firebase.FirebaseApp.DefaultInstance;
    // where app is a Firebase.FirebaseApp property of your application class.

    // Set a flag here indicating that Firebase is ready to use by your
    // application.
  } else {
    UnityEngine.Debug.LogError(System.String.Format(
      "Could not resolve all Firebase dependencies: {0}", dependencyStatus));
    // Firebase Unity SDK is not safe to use here.
  }
});

Build your app

Android

  1. Select the File > Build Settings menu option.
  2. Select Android in the Platform list.
  3. Click Switch Platform to select Android as the target platform.
  4. Wait for the spinner (compiling) icon in the bottom right corner of the Unity status bar to stop.
  5. Click Build and Run.

iOS

  1. Select the File > Build Settings menu option.
  2. Select iOS in the Platform list.
  3. Click Switch Platform to select iOS as the target platform.
  4. Wait for the spinner (compiling) icon in the bottom right corner of the Unity status bar to stop.
  5. Click Build and Run.

Setting up public access

The Realtime Database provides a declarative rules language that allows you to define how your data should be structured, how it should be indexed, and when your data can be read from and written to. By default, read and write access to your database is restricted so only authenticated users can read or write data. To get started without setting up Authentication, you can configure your rules for public access. This does make your database open to anyone, even people not using your app, so be sure to restrict your database again when you set up authentication.

Configuring the SDK for the Unity Editor.

When testing your scene in the Unity Editor, you can use the Realtime Database. You must configure the SDK with the proper database URL. Call SetEditorDatabaseUrl with the url of your database.

using Firebase;
using Firebase.Unity.Editor;

public class MyScript: MonoBehaviour {
  void Start() {
    // Set this before calling into the realtime database.
    FirebaseApp.DefaultInstance.SetEditorDatabaseUrl("https://YOUR-FIREBASE-APP.firebaseio.com/");
  }
}

If you have chosen to use public access for your rules and have set the database url, you can proceed to the sections on saving and retrieving data.

Optional. Editor Setup for restricted access.

If you choose to use rules that disallow public access, you will need to configure the SDK to use a service account to run in the Unity Editor. This will also allow you to impersonate end users while testing. To do this first create a new p12 file via

https://console.cloud.google.com/iam-admin/serviceaccounts/project?project=YOUR-FIREBASE-APP

Record the generated email and password of the service account.

Place the p12 file under "Editor Default Resources" within your Unity project. Next, add the following code to initialize usage of the service account.

using Firebase;
using Firebase.Unity.Editor;

public class MyScript: MonoBehaviour {
  void Start() {
    // Set these values before calling into the realtime database.
    FirebaseApp.DefaultInstance.SetEditorDatabaseUrl("https://YOUR-FIREBASE-APP.firebaseio.com/");
    FirebaseApp.DefaultInstance.SetEditorP12FileName("YOUR-FIREBASE-APP-P12.p12");
    FirebaseApp.DefaultInstance.SetEditorServiceAccountEmail("SERVICE-ACCOUNT-ID@YOUR-FIREBASE-APP.iam.gserviceaccount.com");
    FirebaseApp.DefaultInstance.SetEditorP12Password("notasecret");
  }
}

Next Steps

Known issues

  • When using the experimental .NET 4.6 framework, the Realtime Database does not work on macOS with Unity 2017.2 due to a regression introduced in 2017.2.0 which broke SslStream in that configuration. The regression was fixed in 2017.3.0 and the Realtime Database does work with that version.

Оставить отзыв о...

Текущей странице
Нужна помощь? Обратитесь в службу поддержки.