-1

Trying to create a nested list in c# that can get data from the json file in unity It currently giving me this error

error CS1061: 'List<GameHandler.MyCard>' does not contain a definition for 'decision' and no accessible extension method 'decision' accepting a first argument of type 'List<GameHandler.MyCard>' could be found

I wanted to access that outcome1 array that inside the MyDecision list, but I can only access it up to

void Start()
    {
        CardData cardData = new CardData();
        cardData.card.decision.outcome1 = new int[] { 1, 2, 3 };   
     }

    [Serializable]
    private class CardData
    {
        public List<MyCard> card;
    }

    [Serializable]
    private class MyCard
    {
        public string[] speech;
        public List<MyDecision> decision;
    }

    [Serializable]
    private class MyDecision
    {
        public int[] outcome1;
        public int[] outcome2;
    }

Here is content of my JSON file that I want to access

{
  "CardData" : [
    { "Speech" : ["Hi World."],
      "Decision":[
        {
        "Outcome1":[1,0,0],
        "Outcome2":[0,1,0]
        }
      ]
    },{
      "Speech": ["Hello","World"],
      "Decision":[
        {
        "Outcome1":[1,1,0],
        "Outcome2":[0,1,1]
        }
      ]
    }
  ]
}
ArkuDada
  • 11
  • 2
  • 1
    `cardData.card` is an array, and you are trying to access an item of that array. you need to use something like: `cardData.card[0].decision[0].ourcome1 = new int[] { 1, 2, 3 };` – Catalin Oct 25 '20 at 07:20
  • Where's the *"nested* `List`"? – CoolBots Oct 25 '20 at 07:20
  • 2
    I strongly recommend to use some naming conventions to identify Lists and arrays from other type fields / properties. Example: use plural ( `cards`, `decisions`). – Pac0 Oct 25 '20 at 07:22

1 Answers1

0

Because these are lists you can't access them in the way you're trying to. There are a few options, one is you could use a recursive method call like the one in this question: Iterate through nested list with many layers

The route I would use is by looping through the lists with a ForEach:

cardData
  .card.ForEach(card => 
    card.decision.ForEach((decision) =>
     {
       decision.outcome1 = new int[] { 1, 2, 3 };
      })
    );

There may be some pitfalls to this and you may want to add some error checks, but it seemed to work okay for me.

You should also listen to Pac0, naming is a big part of code readability so having the names as singular when it's a list will get confusing.

b_en
  • 110
  • 1
  • 2
  • 9