I've been searching a lot for this question throughout the last week, but all I could ever find was an answer to the same question but for the android firebase API, which is different from the Unity one.
Here's the code that I'm trying to use to see if a username/value is already in the database:
public void CheckIfUsernameExists(string nick)
{
System.Threading.Tasks.Task t = db.Child("userinfo").Child(nick).GetValueAsync().ContinueWith(task =>
{
if (task.IsFaulted)
{
Debug.LogError(task.Result.ToString() + "faulted");
usernameExists = false;
usernameNotExistsEvent.Invoke();
}
else if (task.IsCompleted)
{
DataSnapshot snapshot = task.Result;
if (snapshot != null)
{
usernameExists = true;
Debug.LogError(task.Result.ToString() + "completed");
usernameExistsEvent.Invoke();
}
else
{
Debug.LogError(task.Result.ToString() + "elsecompleted");
usernameNotExistsEvent.Invoke();
}
}
else if (task.IsCanceled)
{
Debug.LogError(task.Result.ToString() + "canceled");
usernameNotExistsEvent.Invoke();
}
});
}
Where usernameExistsEvent and usernameNotExistsEvent are UnityEvent objects to which I add listeners to do things depending on what the result was.
I'm making a simple online scoreboard, but I don't want two people to have the same username on the scoreboard for logistics purposes, so I'm checking if the username exists prior to letting the user take it.
Here are the rules that I have for that path up on Firebase:
{
"rules": {
"scores": {
".read": "data.child(auth.uid).exists()",
"$user_id": {
".write":"$user_id === auth.uid"
}
},
"userinfo": {
"$user_id": {
".write":"!data.exists()",
".read": "true"
}
}
}
}
For some odd reason, even when the username does not exist, the task is marked as completed, and thus my code doesn't really work.
Any ideas on how to do this easily with Firebase?
Thank you in advance.
I actually found a simple solution. The problem was that whether or not the data actually exists on the database, since you're passing it a key for searching, snapshot will never be null.
There's a good piece of data inside the snapshot object though: the .Exists
. That will tell you if the query actually was in the database or not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With