Not too long ago I was first introduced to Googles Firebase when working on a Madlibs style application. Another member of my team was tasked to make a web application that was a simple input entry form asking for users information and a few words that would later be used to create an adlib. The application was for a live event where adlibs would be shown on a large LED wall every so often after a series of animations. I’m going to run through my workflow on setting up Unity with Firebase and retrieving and parsing through Firebase Data.
After setting up a new Unity project we then need to download the Firebase SDK from Google’s website. Firebase SDK After downloading the SDK and unzipping it you will see a few different Unity packages. We are only going to be using FirebaseDatabase.unitypackge in this project. Go ahead and drag it into your project folder and let it upload. Lastly, im going to use the LitJson C# library to handle my JSON Data. You can download the LitJson.dll from here and place it in your Assets folder. Let us go ahead and create our script that we will write our logic in. First I’m going to start off by adding the using statements for Firebase and LitJson libraries.
The Start function is where you are going to want to setup your Firebase URL and add any event listeners. We are first going to call SetEditorDatabaseUrl with our respective database URL this has to be done before you can access Firebase in any way.
I’m then going to add an event listener. In this case, I’m using the ChildAdded event listener. This will call the HandleChildAdded function when a child is added to your database. The child entries in our database that we want to parse are going to create at the “vetted” location. This can be set by setting the GetReference() function and specifying “vetted”. This helps narrow down the ChildAdded event calls to just when a child is added to the “vetted” location. You could use the RootRefernce instead of GetReference to get the Root location of your Firebase but this isn’t always the best method and is dependant on what else you are using your database for.
//Example getting Children added from reference point in database
FirebaseDatabase.DefaultInstance.GetReference("vetted").ChildAdded += HandleChildAdded;
//Example getting children added from root of your database
FirebaseDatabase.DefaultInstance.RootReference.ChildAdded += HandleChildAdded;
This is the full list of event listeners that are at your disposal in the Firebase SDK
ValueChanged – Read and listen for changes to the entire contents of a path.
ChildAdded – Retrieve lists of items or listen for additions to a list of items. Suggested use with ChildChanged and ChildRemoved to monitor changes to lists.
ChildChanged – Listen for changes to the items in a list. Use with ChildAdded and ChildRemoved to monitor changes to lists.
ChildRemoved – Listen for items being removed from a list. Use with ChildAdded and ChildChanged to monitor changes to lists.
ChildMoved – Listen for changes to the order of items in an ordered list. ChildMoved events always follow the ChildChanged event that caused the item’s order to change ( based on your current order-by method).
Before I set up our HandleChildAdded function I first want to create a class that will be used as a way to contain our parsed JSON.
public class adlib
public string firstName;
public string animalOrAppliance;
public string everyDayActivity;
public string formExercise;
public string funWordToSay;
public string superPower;
public int version;
public string email;
In the following image, you will see our Firebase Database data I’m going to be working with. Ultimately what we are trying to do is instantiate a class for each entry that is added to the database and then fills the values of that class with the respective values in our database. That being said let’s move on and create our HandleChildAdded function.
After declaring our function the first thing we are going to doing is to create a temporary string variable called newChild and set it equal to our raw JSON value from args that are passed into our function. Then we will create a new variable of type JsonSata called singleChild and make that equal to JsonMapper.ToObject(newChild). This will be the variable that we can parse through and assign the data to our variables in our custom class. The next thing we are going to do is create an instance of our adlib class called “user” in this case. Then we will use a try catch to assign all variables of our class in case there are any issues. What is great about using JSON data is we can parse through all the data using keywords wrapped in brackets like [“adlib”] for instance. I’m not going to go through all of them because I’ve included the source code for reference but you can simply assign string values by making them equal to singleChild then working through the JSON data by tree using keywords like singleChild[“adlib”][“firstName”].ToString(). Just know that since you are working with a JsonData variable type you have to convert the data using .ToString() for a string variable once you’ve arrived at the value you want. You can even wrap the entire thing in Int32.Parse to store integer variables as well. Lastly, I added this instance of “user” to my list of adlibs called adlist. Take a look at the included code below to get the full scope of how I setup my HandleChildAdded function as well as a live action shot of our end product.
voidHandleChildAdded(object sender, ChildChangedEventArgs args)
Debug.Log("Adlib added to vetted");
string newChild = args.Snapshot.GetRawJsonValue();
JsoData singleChild = JsonMapper.ToObject(newChild);
adlib user =newadlib();
user.version = Int32.Parse(singleChild["adlib"]["version"].ToString()); }
user.firstName = singleChild["adlib"]["firstName"].ToString();
user.everyDayActivity = singleChild["adlib"]["everyDayActivity"].ToString();
user.animalOrAppliance = singleChild["adlib"]["animalOrAppliance"].ToString();
user.formExercise = singleChild["adlib"]["formExercise"].ToString();
user.funWordToSay = singleChild["adlib"]["funWordToSay"].ToString();
user.superPower = singleChild["adlib"]["superPower"].ToString();
user.email = singleChild["user"]["email"].ToString();