Save Data Stay organized with collections Save and categorize content based on your preferences.
Before you begin
Before you can useRealtime Database,you need to:
Register your Unity project and configure it to use Firebase.
If your Unity project already uses Firebase, then it's alreadyregistered and configured for Firebase.
If you don't have a Unity project, you can download asample app.
Add theFirebaseUnity SDK (specifically,
FirebaseDatabase.unitypackage) toyour Unity project.
Note that adding Firebase to your Unity project involves tasks both in theFirebase console and in your open Unity project(for example, you download Firebase config files from the console, then movethem into your Unity project).
Saving Data
There are five methods for writing data to theFirebase Realtime Database:
| Method | Common uses |
|---|---|
SetValueAsync() | Write or replace data to a defined path, such asusers/<user-id>/<username>. |
SetRawJsonValueAsync() | Write or replace data with raw Json, such asusers/<user-id>/<username>. |
Push() | Add to a list of data. Every time you callPush(), Firebase generates a unique key that can also be used as a unique identifier, such asuser-scores/<user-id>/<unique-score-id>. |
UpdateChildrenAsync() | Update some of the keys for a defined path without replacing all of the data. |
RunTransaction() | Update complex data that could be corrupted by concurrent updates. |
Get a DatabaseReference
To write data to the Database, you need an instance ofDatabaseReference:
usingFirebase;usingFirebase.Database;publicclassMyScript:MonoBehaviour{voidStart(){// Get the root reference location of the database.DatabaseReferencereference=FirebaseDatabase.DefaultInstance.RootReference;}}
Write, update, or delete data at a reference
Basic write operations
For basic write operations, you can useSetValueAsync() to save data to aspecified reference, replacing any existing data at that path. You can use thismethod to pass types that correspond to the available JSON types as follows:
stringlongdoubleboolDictionary<string, Object>List<Object>
If you use a typed C# object, you can use the built inJsonUtility.ToJson()to convert the object to raw Json and callSetRawJsonValueAsync().For example, you may have a User class that looked as follows:
publicclassUser{publicstringusername;publicstringemail;publicUser(){}publicUser(stringusername,stringemail){this.username=username;this.email=email;}}
You can add a user withSetRawJsonValueAsync() as follows:
privatevoidwriteNewUser(stringuserId,stringname,stringemail){Useruser=newUser(name,email);stringjson=JsonUtility.ToJson(user);mDatabaseRef.Child("users").Child(userId).SetRawJsonValueAsync(json);}
UsingSetValueAsync() orSetRawJsonValueAsync() in this way overwrites dataat the specified location, including any child nodes. However, you can stillupdate a child without rewriting the entire object. If you want to allow usersto update their profiles you could update the username as follows:
mDatabaseRef.Child("users").Child(userId).Child("username").SetValueAsync(name);Append to a list of data
Use thePush() method to append data to a list in multiuser applications.ThePush() method generates a unique key every time a newchild is added to the specified Firebase reference. By using theseauto-generated keys for each new element in the list, several clients canadd children to the same location at the same time without write conflicts. Theunique key generated byPush() is based on a timestamp, so list items areautomatically ordered chronologically.
You can use the reference to the new data returned by thePush() method to getthe value of the child's auto-generated key or set data for the child. CallingKey on aPush() reference returns the value of theauto-generated key.
Update specific fields
To simultaneously write to specific children of a node without overwriting otherchild nodes, use theUpdateChildrenAsync() method.
When callingUpdateChildrenAsync(), you can update lower-level child values byspecifying a path for the key. If data is stored in multiple locations to scalebetter, you can update all instances of that data usingdata fan-out. For example, agame might have aLeaderboardEntry class like this:
publicclassLeaderboardEntry{publicstringuid;publicintscore=0;publicLeaderboardEntry(){}publicLeaderboardEntry(stringuid,intscore){this.uid=uid;this.score=score;}publicDictionary<string,Object>ToDictionary(){Dictionary<string,Object>result=newDictionary<string,Object>();result["uid"]=uid;result["score"]=score;returnresult;}}
To create a LeaderboardEntry and simultaneously update it to the recent scorefeed and the user's own score list, the game uses code like this:
privatevoidWriteNewScore(stringuserId,intscore){// Create new entry at /user-scores/$userid/$scoreid and at// /leaderboard/$scoreid simultaneouslystringkey=mDatabase.Child("scores").Push().Key;LeaderBoardEntryentry=newLeaderBoardEntry(userId,score);Dictionary<string,Object>entryValues=entry.ToDictionary();Dictionary<string,Object>childUpdates=newDictionary<string,Object>();childUpdates["/scores/"+key]=entryValues;childUpdates["/user-scores/"+userId+"/"+key]=entryValues;mDatabase.UpdateChildrenAsync(childUpdates);}
This example usesPush() to create an entry in the node containing entries forall users at/scores/$key and simultaneously retrieve the key withKey. The key can then be used to create a second entry in the user'sscores at/user-scores/$userid/$key.
Using these paths, you can perform simultaneous updates to multiple locations inthe JSON tree with a single call toUpdateChildrenAsync(), such as how thisexample creates the new entry in both locations. Simultaneous updates made thisway are atomic: either all updates succeed or all updates fail.
Delete data
The simplest way to delete data is to callRemoveValue() on a reference to thelocation of that data.
You can also delete by specifyingnull as the value for another writeoperation such asSetValueAsync() orUpdateChildrenAsync(). You can use thistechnique withUpdateChildrenAsync() to delete multiple children in a single APIcall.
Know when your data is committed.
To know when your data is committed to theFirebase Realtime Database server, youcan add a continuation. BothSetValueAsync() andUpdateChildrenAsync()return aTask that allows you to know when the operation is complete. If thecall is unsuccessful for any reason, the TasksIsFaulted will be true with theException property indicating why the failure occurred.
Save data as transactions
When working with data that could be corrupted by concurrentmodifications, such as incremental counters, you can use atransaction operation.You give this operation aFunc. This updateFunc takes the current stateof the data as an argument and returns the new desired state you would like towrite. If another client writes to the location before your new value issuccessfully written, your update function is called again with the new currentvalue, and the write is retried.
For instance, in a game you could allow users to update a leaderboard withthe five highest scores:
privatevoidAddScoreToLeaders(stringemail,longscore,DatabaseReferenceleaderBoardRef){leaderBoardRef.RunTransaction(mutableData=>{List<object>leaders=mutableData.ValueasList<object>if(leaders==null){leaders=newList<object>();}elseif(mutableData.ChildrenCount>=MaxScores){longminScore=long.MaxValue;objectminVal=null;foreach(varchildinleaders){if(!(childisDictionary<string,object>))continue;longchildScore=(long)((Dictionary<string,object>)child)["score"];if(childScore <minScore){minScore=childScore;minVal=child;}}if(minScore >score){// The new score is lower than the existing 5 scores, abort.returnTransactionResult.Abort();}// Remove the lowest score.leaders.Remove(minVal);}// Add the new high score.Dictionary<string,object>newScoreMap=newDictionary<string,object>();newScoreMap["score"]=score;newScoreMap["email"]=email;leaders.Add(newScoreMap);mutableData.Value=leaders;returnTransactionResult.Success(mutableData);});}
Using a transaction prevents the leaderboard from being incorrect if multipleusers record scores at the same time or the client had stale data. If thetransaction is rejected, the server returns the current value to the client,which runs the transaction again with the updated value. This repeats until thetransaction is accepted or too many attempts have been made.
Note: BecauseRunTransaction() is called multiple times, it must be able tohandlenull data. Even if there is existing data in your remote database,it may not be locally cached when the transaction function is run, resultinginnull for the initial value.Write data offline
If a client loses its network connection, your app will continue functioningcorrectly.
Every client connected to a Firebase database maintains its own internal versionof any active data. When data is written, it's written to this local versionfirst. The Firebase client then synchronizes that data with the remote databaseservers and with other clients on a "best-effort" basis.
As a result, all writes to the database trigger local events immediately, beforeany data is written to the server. This means your app remainsresponsive regardless of network latency or connectivity.
Once connectivity is reestablished, your app receives the appropriate set ofevents so that the client syncs with the current server state, without having towrite any custom code.
Next Steps
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-12-11 UTC.