Unity Json添加和删除

时间:2020-06-25 14:54:44

标签: json unity3d

我最近开始统一工作json。我设法创建了一个看起来像这样的结构:

enter image description here

我不知道该怎么做:

  • 我应该如何向列表中添加新元素;
  • 如何从列表中删除元素。

这是我正在使用的代码(仍在进行中): enter image description here

对于能帮助我的任何建议,我将不胜感激。

1 个答案:

答案 0 :(得分:1)

对于将来的一般情况:请不要发布代码图片...将其复制并粘贴为文本,并通过{ }按钮将其格式化为代码!


如果要向集合中动态添加项目,请不要使用数组([])!

请使用适当的收集类型,例如成为List,尤其是如果您已经在调用它的列表并且之前已经在代码中包含它;)

public List<PlayerData> playersData = new List<PlayerData>();

我应该如何向列表中添加新元素?

player.playersData.Add(new PlayerData() 
{ 
    _username = "Example Name",
    _user_ip_address = "123.123.123.123",
    _user_score = 42
});

或者甚至添加一个适当的构造函数:

[Serializable]
public class PlayerData
{
    public string _username;
    public string _user_ip_address;
    public float _user_score;

    // You need a parameterless constructor for the (de)serialization
    public PlayerData() { } 

    public PlayerData(string name, string ip, float score)
    {
        _username = name;
        _user_ip_address = ip;
        _user_score = score;
    }
}

现在只是

player.playersData.Add(new PlayerData("Example Name", "123.123.123.123", 42));

如何从列表中删除元素?

List有很多选择:

// by reference
PlayerData somePlayerData;

player.playersData.Remove(somePlayerData);

// or by index
player.playersData.RemoveAt(index);

// or by range
player.playersData.RemoveRange(startIndex, amount);

// or by condition
player.playersData.RemoveAll(element => element._username.StartsWith("Example"));

// or remove all elements
player.playersData.Clear();

更多笔记

  1. 从不对系统文件路径使用字符串concat(+ "/")!

    请使用Path.Combine,它会根据设备的操作系统自动插入正确的路径分隔符。

     var filePath = Path.Combine(Application.dataPath, "dropFile.json");
    
  2. 如果您的目标是该json仅可用于Unity Editor本身,则可以。但是,如果您的目标是在运行时在最终应用程序中读写此文件,则您很可能无权直接在应用程序的安装路径中进行读写。

    →宁可使用Application.persistentDataPath

  3. 在您的read方法中,您可能还希望将已加载的数据转换为字段,例如

     JsonUtility.FromJsonOverwrite(json, player);