0
\$\begingroup\$

I'm saving game data into JSON, however basically I can't get property with just string just like in JavaScript.

This makes my code to write so many if/switch statements, looks very not clean, hard to read.

For instance, if I have this struct to save data as JSON:

public struct PlayerData {
    public int compensator;
    public int silencer;
    ...
}

I want to do something like this:

string attachmentName = "compensator";

if (PlayerData[attachmentName]) {
    weapon[attachmentName].gameObject.SetActive(true);
}

This part:

weapon[attachmentName].gameObject.SetActive(true);

Can do with Dictionary, but this part can't, because it's C# struct/class:

if (PlayerData[attachmentName]) {

Is there a way to access JSON data dynamically in this case?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Since the objects seam to be of the same type, you can just rearrange them into a dictionary for easier access. That way you can do string based lookup.

Or if you don't mind it being (really really) slow, then you can use reflection. The method below returns an object based on the field name you pass in:

public static object GetAttachment(object obj, string fieldName) 
{
    return obj.GetType().GetField(fieldName).GetValue(obj);
}

Use it like this:

GetAttachment(playerData, "compensator");
\$\endgroup\$
5
  • \$\begingroup\$ Could you give me some example code of "rearrange to dictionary"? That's really I want to do, but have no idea how to achieve that. Thanks! \$\endgroup\$
    – modernator
    Jul 18, 2019 at 5:59
  • 1
    \$\begingroup\$ @modernator you create a dictionary with strings as keys and whatever object type you need as values, then you can simply put the values in it by doing yourDictionary.Add("compensator", playerData.compensator). You have to do it manually \$\endgroup\$
    – Bálint
    Jul 18, 2019 at 14:13
  • \$\begingroup\$ Ok, that make sense! However what if I want to set value as well? If I just put the value into the dictionary, I can get the value, but updating inside of dictionary doesn't affect to original data. \$\endgroup\$
    – modernator
    Jul 19, 2019 at 3:57
  • 1
    \$\begingroup\$ @modernator create a setter and update the values there \$\endgroup\$
    – Bálint
    Jul 19, 2019 at 7:20
  • \$\begingroup\$ Thank you so much. I added setter and getter inside of dictionary, now I can access with just key. \$\endgroup\$
    – modernator
    Jul 19, 2019 at 13:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .