Home > Enterprise >  Is it possible to send dynamic "Key" names for "Key: Value" pairs from Unity C#
Is it possible to send dynamic "Key" names for "Key: Value" pairs from Unity C#

Time:06-23

Problem:

The current firebase structure looks like this:

enter image description here

Goal:

From Unity C#, I want the "userID" piece to be dynamic based on a variable.

Question:

Is it possible to send dynamic Key names from Unity C# to Firebase?

Code Example:

public void CreateUser()
{

    userID = user.UserId; //this is the auth userID

    Username UserIDtoUsername = new Username(registerUsername.text, userID);
    string json = JsonUtility.ToJson(UserIDtoUsername);
    dbReference.Child("usernames").SetRawJsonValueAsync(json);

}

public class Username
{
    public string username;
    public string userID;

    public Username(string username, string userID)
    {
        userID = username; //this does not work because we are not passing back the variables
        //need a way to pass back the user's current userID and username to then convert to Json and into Firebase
    }

}

CodePudding user response:

There is no way you can have a dynamic field inside a class. The names of the fields in a class are always predefined. This means that you cannot use an object of the class to get the desired behavior.

Is it possible to send dynamic Key names from Unity C# to Firebase?

Yes, it's possible. If you need to have the actual UID as a key, then you should consider using the following line of code:

dbReference.Child("usernames").Child(userID).SetValueAsync(registerUsername.text);

Assigning the value of username to the userID in the class, will not provide the desired behavior. Will only set the value of userID to the username field.

  • Related