提问者:小点点

在json对象中保存对象数组


null

{
    "name":"Chelsea"
    "players": [
        {
            "name":"Player1"
        },
        {
            "name":"Player2"
        },
        {
            "name":"Player3"
        }
    ]
}

null

{"name":"Chelsea"}

null

public class Team
{
    public string name = "testTeam";
    public Player[] players = new Player[0];

    public void AddPlayer(Player player)
    {
        int i = players.Length;
        players = new Player[i+1];
        players[i] = player;
    }

    public void save()
    {
        File.WriteAllText(Application.dataPath + "/data/teams/" + name + ".json", JsonUtility.ToJson(this));
    }
}

public class Player
{
    public string name;
}

共2个答案

匿名用户

null

public Player[] players = new Player[0];

public void AddPlayer(Player player)
{
    int i = players.Length;
    players = new Player[i+1];
    players[i] = player;
}

null

null

public List<Player> players = new List<Player>();

public void AddPlayer(Player player)
{
    players.Add(player);
}

对于序列化(根据@derhugo的建议),将[Serializable]属性添加到您的类中。

[Serializable]
public class Player
{
    public string name;
}
...

匿名用户

null

null

null

    null

null

null

[Serializable]
public class Team
{
    ...
}

[Serializable]
public class Player
{
    ...
}

null

null

public class Example : MonoBehaviour
{
    public Team team;
}

null

null