Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Firebase SDK

Discussion in 'Scripting' started by squigglyo, Dec 1, 2016.

  1. squigglyo

    squigglyo

    Joined:
    May 21, 2012
    Posts:
    107
    Im running in to some problems trying to use Firebase and running out of time to get them fixed.

    After a LOT of effort, ive got Firebase Auth working.
    By following the guide here
    https://firebase.google.com/docs/auth/


    My problem though if I cant find a way to start using the database once the Auth has taken place.
    Theres the FirebaseDatabase SDK, but that doesnt explain how to incorporate the Auth.

    I got the FirebaseDatabase example project and got that working with my database, but when I put my Auth code in, it logs in, but then looses the ability to put data in.

    Code (CSharp):
    1. // Copyright 2016 Google Inc. All rights reserved.
    2. //
    3. // Licensed under the Apache License, Version 2.0 (the "License");
    4. // you may not use this file except in compliance with the License.
    5. // You may obtain a copy of the License at
    6. //
    7. //     http://www.apache.org/licenses/LICENSE-2.0
    8. //
    9. // Unless required by applicable law or agreed to in writing, software
    10. // distributed under the License is distributed on an "AS IS" BASIS,
    11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12. // See the License for the specific language governing permissions and
    13. // limitations under the License.
    14.  
    15. using Firebase;
    16. using Firebase.Database;
    17. using Firebase.Unity.Editor;
    18. using System;
    19. using System.Collections;
    20. using System.Collections.Generic;
    21. using System.Threading.Tasks;
    22. using UnityEngine;
    23. using UnityEngine.UI;
    24.  
    25. // Handler for UI buttons on the scene.  Also performs some
    26. // necessary setup (initializing the firebase app, etc) on
    27. // startup.
    28. public class UIHandler : MonoBehaviour {
    29.     const string appName = "INSERT FIREBASE PROJECT NAME";
    30.     Firebase.Auth.FirebaseAuth auth;
    31.  
    32.     ArrayList leaderBoard;
    33.     Vector2 scrollPosition = Vector2.zero;
    34.     private Vector2 controlsScrollViewVector = Vector2.zero;
    35.  
    36.     public GUISkin fb_GUISkin;
    37.  
    38.     private const int MaxScores = 5;
    39.     private string logText = "";
    40.     private string email = "";
    41.     private int score = 100;
    42.     private Vector2 scrollViewVector = Vector2.zero;
    43.     bool UIEnabled = true;
    44.  
    45.     const int kMaxLogSize = 16382;
    46.     DependencyStatus dependencyStatus = DependencyStatus.UnavailableOther;
    47.  
    48.     // When the app starts, check to make sure that we have
    49.     // the required dependencies to use Firebase, and if not,
    50.     // add them if possible.
    51.     void Start() {
    52.         dependencyStatus = FirebaseApp.CheckDependencies();
    53.         if (dependencyStatus != DependencyStatus.Available) {
    54.             FirebaseApp.FixDependenciesAsync().ContinueWith(task => {
    55.                 dependencyStatus = FirebaseApp.CheckDependencies();
    56.                 if (dependencyStatus == DependencyStatus.Available) {
    57.                     InitializeFirebase();
    58.                 } else {
    59.                     // This should never happen if we're only using Firebase Analytics.
    60.                     // It does not rely on any external dependencies.
    61.                     Debug.LogError(
    62.                         "Could not resolve all Firebase dependencies: " + dependencyStatus);
    63.                 }
    64.             });
    65.         } else {
    66.             InitializeFirebase();
    67.         }
    68.  
    69.         DebugLog ("Logging in");
    70.         auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
    71.         auth.SignInWithEmailAndPasswordAsync ("Testemail@gmail.com", "ScottsPassword").ContinueWith (task => {
    72.             if (task.IsCompleted && !task.IsCanceled && !task.IsFaulted) {
    73.                 // User is now signed in.
    74.                 DebugLog("Logged in");
    75.                 //Firebase.Auth.FirebaseUser newUser = auth.CurrentUser;
    76.                 //result.Result();
    77.                 //testText.text = "Logged in as: " + auth.CurrentUser.DisplayName;
    78.             } else {
    79.                 DebugLog("Problem logging in");
    80.                 //testText.text = "PROBLEM LOGGING IN!";          
    81.             }
    82.         });
    83.         DebugLog ("Done Logging in");
    84.  
    85.     }
    86.  
    87.     // Initialize the Firebase database:
    88.     void InitializeFirebase() {
    89.         FirebaseApp app = FirebaseApp.DefaultInstance;
    90.         app.SetEditorDatabaseUrl("https://" + appName + ".firebaseio.com/");
    91.  
    92.         leaderBoard = new ArrayList();
    93.         leaderBoard.Add("Firebase Top " + MaxScores.ToString() + " Scores");
    94.         FirebaseDatabase.DefaultInstance
    95.             .GetReference("Leaders").OrderByChild("score")
    96.             .ValueChanged += (object sender2, ValueChangedEventArgs e2) => {
    97.             if (e2.DatabaseError != null) {
    98.                 Debug.LogError(e2.DatabaseError.Message);
    99.                 return;
    100.             }
    101.             string title = leaderBoard[0].ToString();
    102.             leaderBoard.Clear();
    103.             leaderBoard.Add(title);
    104.             if (e2.Snapshot != null && e2.Snapshot.ChildrenCount > 0) {
    105.                 foreach (var childSnapshot in e2.Snapshot.Children) {
    106.                     leaderBoard.Insert(1, childSnapshot.Child("score").Value.ToString()
    107.                         + "  " + childSnapshot.Child("email").Value.ToString());
    108.                 }
    109.             }
    110.         };
    111.  
    112.  
    113.     }
    114.  
    115.     // Exit if escape (or back, on mobile) is pressed.
    116.     void Update() {
    117.         if (Input.GetKeyDown(KeyCode.Escape)) {
    118.             Application.Quit();
    119.         }
    120.     }
    121.  
    122.     // Output text to the debug log text field, as well as the console.
    123.     public void DebugLog(string s) {
    124.         Debug.Log(s);
    125.         logText += s + "\n";
    126.  
    127.         while (logText.Length > kMaxLogSize) {
    128.             int index = logText.IndexOf("\n");
    129.             logText = logText.Substring(index + 1);
    130.         }
    131.  
    132.         scrollViewVector.y = int.MaxValue;
    133.     }
    134.  
    135.     // A realtime database transaction receives MutableData which can be modified
    136.     // and returns a TransactionResult which is either TransactionResult.Success(data) with
    137.     // modified data or TransactionResult.Abort() which stops the transaction with no changes.
    138.     TransactionResult AddScoreTransaction(MutableData mutableData) {
    139.         DebugLog("Inside Transaction Function...");
    140.  
    141.         List<object> leaders = mutableData.Value as List<object>;
    142.  
    143.         if (leaders == null) {
    144.             leaders = new List<object>();
    145.             } else if (mutableData.ChildrenCount >= MaxScores) {
    146.                 // If the current list of scores is greater or equal to our maximum allowed number,
    147.             // we see if the new score should be added and remove the lowest existing score.
    148.             long minScore = long.MaxValue;
    149.             object minVal = null;
    150.                 foreach (var child in leaders) {
    151.                 if (!(child is Dictionary<string, object>))
    152.                     continue;
    153.                 long childScore = (long)((Dictionary<string, object>)child)["score"];
    154.                 if (childScore < minScore) {
    155.                     minScore = childScore;
    156.                     minVal = child;
    157.                 }
    158.             }
    159.        
    160.             // If the new score is lower than the current minimum, we abort.
    161.             if (minScore > score) {
    162.                 return TransactionResult.Abort();
    163.             }
    164.             // Otherwise, we remove the current lowest to be replaced with the new score.
    165.             leaders.Remove(minVal);
    166.         }
    167.  
    168.         // Now we add the new score as a new entry that contains the email address and score.
    169.         Dictionary<string, object> newScoreMap = new Dictionary<string, object>();
    170.         newScoreMap["score"] = score;
    171.         newScoreMap["email"] = email;
    172.         leaders.Add(newScoreMap);
    173.  
    174.         // You must set the Value to indicate data at that location has changed.
    175.         mutableData.Value = leaders;
    176.         return TransactionResult.Success(mutableData);
    177.     }
    178.  
    179.     public void AddScore() {
    180.         if (score == 0 || string.IsNullOrEmpty(email)) {
    181.             DebugLog("invalid score or email.");
    182.             return;
    183.         }
    184.         DebugLog(String.Format("Attempting to add score {0} {1}",
    185.             email, score.ToString()));
    186.  
    187.         DatabaseReference reference = FirebaseDatabase.DefaultInstance.GetReference("Leaders");
    188.  
    189.  
    190.         DebugLog("Running Transaction...");
    191.         // Use a transaction to ensure that we do not encounter issues with
    192.         // simultaneous updates that otherwise might create more than MaxScores top scores.
    193.         try
    194.         {
    195.         reference.RunTransaction(AddScoreTransaction)
    196.             .ContinueWith(task => {
    197.                 DebugLog("Inside Transaction...");
    198.                 if (task.Exception != null) {
    199.                     DebugLog(task.Exception.ToString());
    200.                 } else if (task.IsCompleted) {
    201.                     DebugLog("Transaction complete.");
    202.                 }
    203.             });
    204.         }catch (Exception e) {
    205.             DebugLog (e.ToString ());
    206.         }
    207.     }
    208.  
    209.     // Render the log output in a scroll view.
    210.     void GUIDisplayLog() {
    211.         scrollViewVector = GUILayout.BeginScrollView(scrollViewVector);
    212.         GUILayout.Label(logText);
    213.         GUILayout.EndScrollView();
    214.     }
    215.  
    216.     // Render the buttons and other controls.
    217.     void GUIDisplayControls() {
    218.         if (UIEnabled) {
    219.             controlsScrollViewVector =
    220.                 GUILayout.BeginScrollView(controlsScrollViewVector);
    221.             GUILayout.BeginVertical();
    222.             GUILayout.BeginHorizontal();
    223.             GUILayout.Label("Email:", GUILayout.Width(Screen.width * 0.20f));
    224.             email = GUILayout.TextField(email);
    225.             GUILayout.EndHorizontal();
    226.  
    227.             GUILayout.Space(20);
    228.  
    229.             GUILayout.BeginHorizontal();
    230.             GUILayout.Label("Score:", GUILayout.Width(Screen.width * 0.20f));
    231.             int.TryParse(GUILayout.TextField(score.ToString()), out score);
    232.             GUILayout.EndHorizontal();
    233.  
    234.             GUILayout.Space(20);
    235.  
    236.             if (!String.IsNullOrEmpty(email) && GUILayout.Button("Enter Score")) {
    237.                 AddScore();
    238.             }
    239.             GUILayout.EndVertical();
    240.             GUILayout.EndScrollView();
    241.         }
    242.     }
    243.  
    244.     void GUIDisplayLeaders() {
    245.         GUI.skin.box.fontSize = 36;
    246.         scrollPosition = GUILayout.BeginScrollView(scrollPosition, false, true);
    247.         GUILayout.BeginVertical(GUI.skin.box);
    248.  
    249.         foreach (string item in leaderBoard) {
    250.             GUILayout.Label(item, GUI.skin.box, GUILayout.ExpandWidth(true));
    251.         }
    252.  
    253.         GUILayout.EndVertical();
    254.         GUILayout.EndScrollView();
    255.     }
    256.  
    257.     // Render the GUI:
    258.     void OnGUI() {
    259.         GUI.skin = fb_GUISkin;
    260.         if (dependencyStatus != DependencyStatus.Available) {
    261.             GUILayout.Label("One or more Firebase dependencies are not present.");
    262.             GUILayout.Label("Current dependency status: " + dependencyStatus.ToString());
    263.             return;
    264.         }
    265.         Rect logArea, controlArea, leaderBoardArea;
    266.  
    267.         if (Screen.width < Screen.height) {
    268.             // Portrait mode
    269.             controlArea = new Rect(0.0f, 0.0f, Screen.width, Screen.height * 0.5f);
    270.             leaderBoardArea = new Rect(0, Screen.height * 0.5f, Screen.width * 0.5f, Screen.height * 0.5f);
    271.             logArea = new Rect(Screen.width * 0.5f, Screen.height * 0.5f, Screen.width * 0.5f, Screen.height * 0.5f);
    272.         } else {
    273.             // Landscape mode
    274.             controlArea = new Rect(0.0f, 0.0f, Screen.width * 0.5f, Screen.height);
    275.             leaderBoardArea = new Rect(Screen.width * 0.5f, 0, Screen.width * 0.5f, Screen.height * 0.5f);
    276.             logArea = new Rect(Screen.width * 0.5f, Screen.height * 0.5f, Screen.width * 0.5f, Screen.height * 0.5f);
    277.         }
    278.  
    279.         GUILayout.BeginArea(leaderBoardArea);
    280.         GUIDisplayLeaders();
    281.         GUILayout.EndArea();
    282.  
    283.         GUILayout.BeginArea(logArea);
    284.         GUIDisplayLog();
    285.         GUILayout.EndArea();
    286.  
    287.         GUILayout.BeginArea(controlArea);
    288.         GUIDisplayControls();
    289.         GUILayout.EndArea();
    290.     }
    291. }
    292.  
    I dont know if maybe im supposed to have something set up in Firebase first, perhaps its expecting certain fields to already exist when the auth is being used?

    I dont even need a database that works like this one. All I need is just
    • List of Players (listed with a uniqueID I create)
    • Some info inside each player
    • A way to dynamically add/update up to 100 random values in to that player
    It would look like
    • Players
      • GHDH5673
        • username
        • email
        • isWinner
        • RandomCheck1
        • Ranbdomcheck2
        • etc
      • GJDK6141
      • etc

    • If anyone can help me out, that would be great. I am days away from needing this project delivered, secure and fully functional.
      • If anyone reckons they could help me out in a bigger capacity by creating a script for me that would simplify all of this stuff, send me a message to see if you can make what I need and ide be open to working something out to make it worth your time.
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,186
    I am not familiar with Firebase. At work we use PlayFab and Heroic Labs for some of our projects that require info online.
    That may not be of much help, but they are both fairly easy to use, have free tiers, and work fairly decent.

    Hopefully someone with Firebase knowledge can help you out. I only suggested these other two in case you think they may work for you and you don't have to use Firebase.