怎么在unity3D工程中导入Newtonsoft.Json

怎么在unity3D工程中导入Newtonsoft.Json

unity旧版本自带的json接口太难用了(JsonUtility),不能序列化字典和列表等对象,只能序列化基础类型对象,所以基本等于没有。

  • Newtonsoft.Json-for-Unity-master

    的github下载地址点这里

  • 或者这个链接,据说是2022版本之后得到了unity官方的支持

在git上下载Newtonsoft.Json-for-Unity-master的压缩文件(.zip),解压之后,复制到unity3D工程的Asset/Plugins文件夹下就可以用了,

在这里插入图片描述

在脚本中就可以使用Newtonsoft.Json了,例如下述代码:

using System.Collections.Generic;
using UnityEngine;
using Newtonsoft.Json;
using System.IO;

public class Player : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        string json = JsonConvert.SerializeObject(
            new Dictionary {
                { "123", "123" },{ "456", "456" }, });
        string path = Application.persistentDataPath + "/saveFile.json";
        File.WriteAllText(path, json);

    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

经过验证,上述方法不行(具体原因后续查),可以采用如下方式安装json包

  • 打开 Unity 编辑器。

  • 转到菜单栏的 “Window”(窗口)选项,然后选择 “Package Manager”(包管理器)。

  • 在 Package Manager 窗口中,选择 “All”(全部)选项卡。

  • 在搜索框中输入 “Json.NET” 或 “Newtonsoft.Json” 进行搜索。

  • 在搜索结果中,应该会看到 “Json.NET for Unity” 或类似名称的项目。

  • 单击搜索结果下方的 “Install”(安装)按钮。

  • 等待 Unity 下载并安装 Newtonsoft.Json 包。

在2022.3.2f1c1中亲测可以

本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://www.net2asp.com/dedbcddcc1.html