[System.Serializable]
public class Character
{
public string id;
public int Atk;
public int Hp;
public int Def;
}
[System.Serializable]
public class CharacterList
{
public Character[] characters;
}
public Characterlist charlist = new CharacterList();
void Start()
{
charlist = JsonUtility.FromJson<CharacterList>("Assets/data.json".text);
}
in this code, I can run out the character list in the gameObject.
However, i dont know how to get the whole class data by one of the elements ( such as “id”)
For example, to get
{
id = “a1”
int = 1
Hp = 3
Def = 4
}
Well, that’s debatable. You probably know the type System.Collections.Generic.List<T>, right? Guess what, it’s a class that contains an array and is named List ^^.
Since for proper deserialization (with the JsonUtility) you need a wrapping class for the root element, I don’t really see an issue with that name. Others may have given the class a generic name like “CharacterData” which tells you even less.
Interesting, I didn’t realize what’s under the hood of the List. Anyway, I think that CharacterRepository as @Kurt-Dekker is a much better name, as it doesn’t confuse with the list’s existence.
When i used the Linq, The CS1061 is appear. How can I do
error CS1061: ‘?.CharacterList’ does not contain a definition for ‘FirstOrDefault’ and no accessible extension method ‘FirstOrDefault’ accepting a first argument of type ‘?.CharacterList’ could be found (are you missing a using directive or an assembly reference?)
I’m sorry about that. I think the problem is happened on
[System.Serializable]
public class CharacterList
{
public Character[] characters;
}
public Characterlist charlist = new CharacterList();
which mean the charlist is not the array or list, which is a class named “CharacterList”
I don’t know am I understand correctly. But if that is correct, how can I solve the problem?