当前位置: 首页 > news >正文

Unity json反序列化为 字典存储

当在Unity游戏中需要加载和管理游戏数据,通常使用JSON文件是一种常见的方法。在本篇博客中,我们将深入探讨如何使用C#和Unity的JSON反序列化功能来实现这一目标。我们可以使用Unity的JsonUtility来反序列化JSON数据并将其映射到自定义的C#数据结构中。

首先,让我们来创建一些数据类,以便加载和管理游戏中的角色和武器数据。在这个示例中,我们将使用Player(角色)、Monster(怪物)和WeaponData(武器数据)这三种数据类型。

{"players": [{"id": "1","name": "player0","weaponID": "102","maxHp": "50","damage": "0","defense": "0","moveSpeed": "5.0","coolDown": "0","amount": "0"},{"id": "2","name": "player1","weaponID": "101","maxHp": "40","damage": "-10","defense": "0","moveSpeed": "5","coolDown": "20","amount": "0"},{"id": "3","name": "player2","weaponID": "101","maxHp": "50","damage": "20","defense": "1","moveSpeed": "5.0","coolDown": "-50","amount": "1"},{"id": "4","name": "player3","weaponID": "102","maxHp": "50","damage": "-50","defense": "-1","moveSpeed": "6","coolDown": "100","amount": "0"}]
} 

我们需要创建了具有与JSON数据匹配的数据结构。这些类使用[Serializable]特性,以便能够进行JSON序列化和反序列化

[Serializable]public class Monster{public int id;public string name;public int maxHp;public int damage;public int defense;public float moveSpeed;public int expMul;}`在这里插入代码片`

通过观察JSON文件我们发现,这个JSON文件示例是一个包含多个玩家信息的数组。

[Serializable]public class PlayerData{public List<Player> players = new List<Player>();}

我们可以用一个玩家数据结构的数组去存储这个json文件,并

TextAsset textAsset = Managers.Resource.Load<TextAsset>($"Data/PlayerData");
PlayerData []players JsonUtility.FromJson<Loader>(textAsset.text);

去解析并且遍历它放到字典里,
当我们要解析的json特别多时 我们定义了一个泛型方法LoadJson,该方法负责加载JSON数据并将其反序列化为具体类型的字典。这个方法接受一个Loader类型,该类型必须实现ILoader接口。

 Loader LoadJson<Loader, Key, Value>(string path) where Loader : ILoader<Key, Value>{TextAsset textAsset = Managers.Resource.Load<TextAsset>($"Data/{path}");return JsonUtility.FromJson<Loader>(textAsset.text);}

ILoader接口

public interface ILoader<Key, Value>
{Dictionary<Key, Value> MakeDict();
}

我们让存储具有JSON数据结构的数组继承该接口

	[Serializable]public class PlayerData : ILoader<int, Player>{public List<Player> players = new List<Player>();public Dictionary<int, Player> MakeDict(){Dictionary<int, Player> dict = new Dictionary<int, Player>();foreach (Player player in players)dict.Add(player.id, player);return dict;}}

这样就可以将JSON文件反序列化放在数组中

 public Dictionary<int, Data.WeaponData> WeaponData { get; private set; } = new Dictionary<int, Data.WeaponData>();public Dictionary<int, Data.Player> PlayerData { get; private set; } = new Dictionary<int, Data.Player>();public Dictionary<int, Data.Monster> MonsterData { get; private set; } = new Dictionary<int, Data.Monster>();public void Init(){PlayerData = LoadJson<Data.PlayerData, int, Data.Player>("PlayerData").MakeDict();WeaponData = LoadJson<Data.WeaponDataLoader, int, Data.WeaponData>("WeaponData").MakeDict();MonsterData = LoadJson<Data.MonsterData, int, Data.Monster>("MonsterData").MakeDict();}

代码如下

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public interface ILoader<Key, Value>
{Dictionary<Key, Value> MakeDict();
}public class DataManager
{public Dictionary<int, Data.WeaponData> WeaponData { get; private set; } = new Dictionary<int, Data.WeaponData>();public Dictionary<int, Data.Player> PlayerData { get; private set; } = new Dictionary<int, Data.Player>();public Dictionary<int, Data.Monster> MonsterData { get; private set; } = new Dictionary<int, Data.Monster>();public void Init(){PlayerData = LoadJson<Data.PlayerData, int, Data.Player>("PlayerData").MakeDict();WeaponData = LoadJson<Data.WeaponDataLoader, int, Data.WeaponData>("WeaponData").MakeDict();MonsterData = LoadJson<Data.MonsterData, int, Data.Monster>("MonsterData").MakeDict();}Loader LoadJson<Loader, Key, Value>(string path) where Loader : ILoader<Key, Value>{TextAsset textAsset = Managers.Resource.Load<TextAsset>($"Data/{path}");return JsonUtility.FromJson<Loader>(textAsset.text);}}

在DataManager的Init方法中,我们加载并初始化了游戏数据,包括角色数据、武器数据和怪物数据。通过调用LoadJson泛型方法,我们可以轻松地加载各种类型的JSON数据并将其转化为字典对象。

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;namespace Data
{#region Character[Serializable]public class Player{public int id;public string name;public int weaponID;public int maxHp;public int damage;public int defense;public float moveSpeed;public int coolDown;public int amount;}[Serializable]public class PlayerData : ILoader<int, Player>{public List<Player> players = new List<Player>();public Dictionary<int, Player> MakeDict(){Dictionary<int, Player> dict = new Dictionary<int, Player>();foreach (Player player in players)dict.Add(player.id, player);return dict;}}#endregion#region Monster[Serializable]public class Monster{public int id;public string name;public int maxHp;public int damage;public int defense;public float moveSpeed;public int expMul;}public class MonsterData : ILoader<int, Monster>{public List<Monster> monsters = new List<Monster>();public Dictionary<int, Monster> MakeDict(){Dictionary<int, Monster> dict = new Dictionary<int, Monster>();foreach (Monster monster in monsters)dict.Add(monster.id, monster);return dict;}}#endregion#region Weapon[Serializable]public class WeaponData{public int weaponID;public string weaponName;public List<WeaponLevelData> weaponLevelData = new List<WeaponLevelData>();}[Serializable]public class WeaponLevelData{public int level;public int damage;public float movSpeed;public float force;public float cooldown;public float size;public int penetrate;public int countPerCreate;}[Serializable]public class WeaponDataLoader : ILoader<int, WeaponData>{public List<WeaponData> weapons = new List<WeaponData>();public Dictionary<int, WeaponData> MakeDict(){Dictionary<int, WeaponData> dict = new Dictionary<int, WeaponData>();foreach (WeaponData weapon in weapons)dict.Add(weapon.weaponID, weapon);return dict;}}#endregion}

通过使用Unity的JsonUtility和C#的泛型方法,我们可以方便地加载和管理游戏数据。这种方法对于处理不同类型的数据非常有用,而且代码可复用性很高。希望这篇博客对你了解Unity中的JSON反序列化和数据管理有所帮助。如果你有任何问题或需要进一步的指导,请随时在评论中提问!

相关文章:

Unity json反序列化为 字典存储

当在Unity游戏中需要加载和管理游戏数据&#xff0c;通常使用JSON文件是一种常见的方法。在本篇博客中&#xff0c;我们将深入探讨如何使用C#和Unity的JSON反序列化功能来实现这一目标。我们可以使用Unity的JsonUtility来反序列化JSON数据并将其映射到自定义的C#数据结构中。 …...

助力青少年学习,亚马逊云科技2024年全球人工智能和机器学习奖学金计划正式启动

云未来将以何种方式发展&#xff1f;方向握在意气风发的少年们手中。近日&#xff0c;亚马逊云科技全球人工智能和机器学习&#xff08;AI和ML&#xff09;奖学金计划在中国区的首次颁奖以及2024年启动仪式在北京中学正式举行&#xff0c;有45名学子凭借杰出的学业成绩、对人工…...

华为机试练习题:HJ13 句子逆序

1、完整题目 HJ13 句子逆序 描述 将一个英文语句以单词为单位逆序排放。例如“I am a boy”&#xff0c;逆序排放后为“boy a am I” 所有单词之间用一个空格隔开&#xff0c;语句中除了英文字母外&#xff0c;不再包含其他字符 数据范围&#xff1a;输入的字符串长度满足…...

windows环境下安装Java过程(免登录Oracle官网下载java)

下载路径 oracle官网&#xff1a; java下载路径 Oracle共享账号可下载JDK&#xff1a; 指路 安装流程 执行下载后的jdk的可执行文件一路next下去&#xff0c; 可以自定义安装路径添加环境变量&#xff0c; 两个地方需要添加 在cmd中输入java -version 进行验证&#xff0c;…...

openssl交叉编译 (ubuntu+arm)

1.下载安装包 wget https://www.openssl.org/source/openssl-1.1.1w.tar.gz 2.解压安装包 tar -zxvf openssl-1.1.1l.tar.gz 3.进入源码文件夹-修改编译器 CCarm-linux-gnueabihf-gcc 4.配置编译参数 ./config no-asm -shared --prefix/home/alientek/sp_test/openssl/sp…...

Python 海龟绘图基础教学教案(十七)

Python 海龟绘图——第 34 题 题目&#xff1a;绘制下面的图形 解析&#xff1a; 使用循环绘制楼梯形。 答案&#xff1a; Python 海龟绘图——第 35 题 题目&#xff1a;绘制下面的图形 解析&#xff1a; 使用二重循环绘制四个方块。 答案&#xff1a;...

element ui多选框(Checkbox 多选框、Select多选框)编辑时无法选中的解决办法

1. Checkbox 多选框无法选中的解决办法: <!--v-model绑定的值必须是[],不能是字符串--><el-form-item label="配布对象" prop="reptGroupArray" > <!--多选--><el-checkbox-group v-model="form.reptGroupArray" size=&q…...

TCP/IP--七层通信

文章目录 TCP/IP--七层通信先来看一下会话层以上的处理再来看一下传输层以下的处理 TCP/IP–七层通信 下面举例说明7层网络模型的功能。假设使用主机A的用户A要给使用主机B的用户B发送一封电子邮件。 在七层OSI模型中&#xff0c;如何模块化通信传输&#xff1f; 先来看一下七…...

汽车标定技术(五)--基于模型开发如何生成完整的A2L文件(1)

1 数据对象的创建 CtrlH打开Model Explorer&#xff0c;在Base workspace中点击工具栏add&#xff0c;出现如下界面&#xff0c; 可以看到Simulink提供了多种数据类型 Matlab Variable&#xff1a;Simulink.Parameter&#xff1a;使用该数据对象表示工程应用中的标定量Simuli…...

重启某个节点、重启电脑服务器后,kubernetes无法运行,k8s无法运行

问题描述 环境&#xff1a;ubuntu18.04 LTS 现象&#xff1a;按步骤安装kubernetes后&#xff0c;正常启动&#xff0c;各个命令均可正常使用。服务器重启后&#xff0c;执行命令错误信息如下&#xff1a; sudo kubectl get nodesThe connection to the server 127.0.0.1:644…...

【ARMv8 SIMD和浮点指令编程】浮点加减乘除指令——四则运算

浮点指令有专门的加减乘除四则运算指令,比如 FADD、FSUB、FMUL、FDIV 等。 1 FADD (scalar) 浮点加法(标量)。该指令将两个源 SIMD&FP 寄存器的浮点值相加,并将结果写入目标 SIMD&FP 寄存器。 该指令可以产生浮点异常。根据 FPCR 中的设置,异常会导致在 FPSR 中…...

JDBC SQL Server Source Connector: 一览与实践

在快速发展的数据驱动业务环境中&#xff0c;确保数据在各个系统间高效、准确地同步至关重要。为了进一步的数据处理和分析&#xff0c;经常需要将这些数据同步到其他数据处理系统。Apache SeaTunnel 提供了一个强大而灵活的数据集成框架&#xff0c;使得从 SQL Server 到其他系…...

WebDAV之π-Disk派盘 + Keepass2Android

推荐一款密码管理器,允许人们使用复杂的组合进行登录,而不必记住所有的组合。 Keepass2Android可以支持大多数安卓互联网浏览器, Android设备上同步软件,还支持通过WebDAV添加葫芦儿派盘。 Keepass2Android 目前安全方面最大的问题之一是大多数人几乎在任何地方都使用通用…...

AspectJX - Android开发平台的AOP框架

官网 GitHub - HujiangTechnology/gradle_plugin_android_aspectjx: A Android gradle plugin that effects AspectJ on Android project and can hook methods in Kotlin, aar and jar file. 项目简介 一个基于AspectJ并在此基础上扩展出来可应用于Android开发平台的AOP框架…...

【TDK 电容 】介电质 代码 对应温度及变化率

JB 电解质是什么&#xff1f;没找到&#xff0c;只有TDK有&#xff0c;也只有这个温度的区别&#xff0c;并且已经停产在售。 对比发现是mouser网站关于电容的描述错误。下图显示正确的&#xff0c;再然后是错误的。 在TDK官网&#xff0c;这样的描述 温度特性 分类标准代码温…...

随笔--解决ubuntu虚拟环境的依赖问题

文章目录 问题一&#xff1a;在conda虚拟环境中报错ImportError: libcupti.so.11.7:cannot open shared object file: No such file or directory解决步骤问题二&#xff1a; RuntimeError: CUDA error: CUBLAS_STATUS_INVALID_VALUE when calling cublasSgemmStridedBatched( …...

Gin学习笔记

Gin学习笔记 Gin文档&#xff1a;https://pkg.go.dev/github.com/gin-gonic/gin 1、快速入门 1.1、安装Gin go get -u github.com/gin-gonic/gin1.2、main.go package mainimport ("github.com/gin-gonic/gin""net/http" )func main() {// 创建路由引…...

使用 OpenTracing 和 LightStep 监控无服务器功能

无服务器功能的采用在企业组织内达到了创纪录的水平。有趣的是&#xff0c;鉴于越来越多的采用和兴趣&#xff0c;许多监控解决方案孤立了在这些环境中执行的代码的性能&#xff0c;或者仅提供有关执行的基本指标。为了了解应用程序的性能&#xff0c;我想知道存在哪些瓶颈、时…...

Sleep(0)、Sleep(1)、SwitchToThread()

当 timeout 参数为 0 时&#xff08;如 Sleep(0)&#xff09;&#xff0c;操作系统会检查可运行队列中是否有高于或等于当前线程优先级的其他就绪线程。如果有&#xff0c;当前线程将被移除并放弃处理器时间&#xff0c;让其他线程执行。如果没有高优先级的线程&#xff0c;当前…...

前端食堂技术周刊第 103 期:10 月登陆 Web 平台的新功能、TS 5.3 RC、React 2023 状态、高并发的哲学原理、Web 资源加载优先级

美味值&#xff1a;&#x1f31f;&#x1f31f;&#x1f31f;&#x1f31f;&#x1f31f; 口味&#xff1a;夏梦玫珑 食堂技术周刊仓库地址&#xff1a;https://github.com/Geekhyt/weekly 大家好&#xff0c;我是童欧巴。欢迎来到前端食堂技术周刊&#xff0c;我们先来看下…...

为什么92%的Sora 2初学者卡在第4步?——帧一致性崩塌诊断工具包+时间轴锚点校准法

更多请点击&#xff1a; https://kaifayun.com 第一章&#xff1a;Sora 2视频生成的核心原理与环境准备 Sora 2并非OpenAI官方发布的模型&#xff0c;而是社区基于Sora技术理念构建的开源复现与增强框架&#xff0c;其核心依托于时空联合建模的扩散变换器&#xff08;Spacetim…...

Python基础语法:访问器@property和修改器@xxx.setter

一、简介 访问器和修改器也是装饰器的一种。 property: 访问器&#xff0c;getter xxx.setter: 修改器&#xff0c;setter 访问器和修改器的根本目的是想将属性私有化&#xff0c;提供getter&setter去访问。 访问器和修改器能够做到访问属性其实在调用getter方法&#xff0…...

除了ulimit -c unlimited:深入理解Linux core dump机制与高级配置指南

深入Linux核心转储&#xff1a;从基础配置到生产环境实战指南当服务器上的关键应用突然崩溃时&#xff0c;系统管理员最需要的就是一份完整的"事故现场记录"。Linux的core dump机制正是为此而生&#xff0c;它能保存程序崩溃时的内存状态、寄存器值和调用堆栈&#x…...

作业本耐用度差距巨大?深圳大明印刷厂拆解合规工艺,告别定制作业本掉页开裂通病

在校园日常教学中&#xff0c;很多学校都会遇到同一个难题&#xff1a;同一学期采购的作业本、定制作业本&#xff0c;品质差距悬殊&#xff0c;有的完好无损用到期末&#xff0c;有的短短几周就出现书脊开裂、页面脱落、边角破损、翻页卡顿等问题。不少人误以为是学生使用习惯…...

三十岁想从零转行现实吗?带你分辨真正有前景的好工作

![](https://img-blog.csdnimg.cn/direct/b0bfa28b59f9478dae4e6feee6659cce.png)我是29岁那年&#xff0c;完成从转行裸辞副业的职业转型。 如果你把职业生涯看成是从现在开始30岁&#xff0c;到你退休那年&#xff0c;中间这么漫长的30年&#xff0c;那么30岁转行完全来得及…...

6款高效降AI率工具 改写实力出众

写论文时反复检测出的AI痕迹总让你提心吊胆&#xff1f;别担心&#xff0c;这里整理了6款真正好用的论文降AI率工具&#xff0c;堪称应对AI生成特征的“得力助手”。它们能有效识别并消除AI生成的痕迹&#xff0c;改写能力出众&#xff0c;帮你快速降低查重率&#xff0c;顺利通…...

[智能体-81]:工程化智能体 = 模型做脑力拆解 + 框架做流程落地。前者是决策者,后者是管理者,tools/function call是内部员工;mcp server是外部资源;

一、全角色人设 & 对应技术组件角色定位对应技术模块核心职责决策者&#xff08;脑力大脑&#xff09;大模型 LLM理解目标、任务拆解、逻辑判断、分支决策、内容生成&#xff0c;负责 “想方案、定步骤”管理者&#xff08;流程总管&#xff09;智能体编排框架&#xff08;…...

保姆级教程:Windows系统下Arcgis 10.2从下载、安装到汉化一次搞定(附常见License启动失败解决方案)

Windows系统下Arcgis 10.2完整安装与汉化实战指南第一次接触Arcgis的新手往往会被复杂的安装流程和神秘的License Manager搞得晕头转向。作为一款功能强大的地理信息系统软件&#xff0c;Arcgis在科研、城市规划、环境监测等领域有着广泛应用&#xff0c;但它的安装过程确实会让…...

Go开发者必备:circuitbreaker API全解析与最佳实践指南 [特殊字符]

Go开发者必备&#xff1a;circuitbreaker API全解析与最佳实践指南 &#x1f680; 【免费下载链接】circuitbreaker Circuit Breakers in Go 项目地址: https://gitcode.com/gh_mirrors/circ/circuitbreaker 作为一名Go开发者&#xff0c;你是否经常遇到远程服务调用失败…...

Taotoken的稳定性与低延迟在实时对话应用中的实际体验

&#x1f680; 告别海外账号与网络限制&#xff01;稳定直连全球优质大模型&#xff0c;限时半价接入中。 &#x1f449; 点击领取海量免费额度 Taotoken的稳定性与低延迟在实时对话应用中的实际体验 在开发需要快速响应的AI聊天应用时&#xff0c;后端API的稳定性和延迟表现是…...