Hello!
So I have a C# script which literally does nothing, and I can’t figure out why.
public TextAsset jsonFile;
Item item = new Item();
public string contents;
void Start()
{
item.coin = new ItemData();
item.coin.chance = 20.0f;
item.coin.minDepth = 0.2f;
item.coin.maxDepth = 6.7f;
contents = JsonUtility.ToJson(item, true); // contents = {}
Debug.Log("contents: " + contents); //contents: {}
loadData();
}
void loadData()
{
item = JsonUtility.FromJson<Item>(contents);
Debug.Log("loadData: " + item.coin.chance + " " + item.coin.minDepth + " " + item.coin.maxDepth); //NullReferenceException: Object reference not set to an instance of an object
}
[System.Serializable]
public class ItemData
{
public float chance { get; set; }
public float minDepth { get; set; }
public float maxDepth { get; set; }
}
public class Item
{
public ItemData coin { get; set; }
}
And my desired JSON output is:
{
"coin":{
"chance": 20.0,
"mindepth": 0.2,
"maxDepth": 6.7
},
"coinSmall":{
"chance": 40.0,
"mindepth": 0.2,
"maxDepth": 6.7
},
"coinBig":{
"chance": 40.0,
"mindepth": 3.2,
"maxDepth": 9.5
}
// Much more coin.
}
So, how could I achieve it? I’m not familiar with C#, I’m learning it now. In python, and Java I can do it, but in C# OMG I can’t.
Please help me!!