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

⭐Unity 安卓环境中正确地读取和处理 XML 文件

写了一个选择题Demo,电脑包和编辑器内无问题,但是打包安卓手机之后题目无法正常使用,想到的是安卓环境中正确地读取文件的问题
 

改进方案:

1.由于 XmlDocument.Load 方法在 Android 上的路径问题(由于文件位于 APK 内部,无法像在文件系统中那样直接访问),需要先使用 UnityWebRequest 来异步加载文件内容,然后再解析 XML。

2.异步处理:修改你的代码,以支持异步文件加载和处理,这对于避免在加载大文件时造成的界面冻结也很有帮助。

代码对比:

初版:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Xml;
using System.Text;public class xmlres : MonoBehaviour
{[SerializeField]private List<Toggle> toggleList;//答案ABC[SerializeField]private Text TM_Text;//题目[SerializeField]private List<Text> DA_TextList;//选项private int topNumber = 0;private string selectAnswer = " ";private bool isSelect = false;//是否选中/* 确定五道题    */List<xmlData> xmls = new List<xmlData>();List<xmlData> useArray = new List<xmlData>();HashSet<xmlData> xmlDatas = new HashSet<xmlData>();//public GameObject selectPanel;//public GameObject wrongPanel;public static xmlres instance;private void Awake(){instance = this;}void Start(){ReadQuestion();toggleList[0].onValueChanged.AddListener(OnValChanged0);toggleList[1].onValueChanged.AddListener(OnValChanged1);toggleList[2].onValueChanged.AddListener(OnValChanged2);}void OnValChanged0(bool check){//Debug.Log(check);if (check){selectAnswer = "A";isSelect = true;}}void OnValChanged1(bool check){//Debug.Log(check);if (check){selectAnswer = "B";isSelect = true;}}void OnValChanged2(bool check){//Debug.Log(check);if (check){selectAnswer = "C";isSelect = true;}}public void ReadQuestion(){string url = Application.streamingAssetsPath + "/myxml.xml";XmlDocument XmlDoc = new XmlDocument();XmlDoc.Load(url);//获取所有题目int XmlCount = XmlDoc.GetElementsByTagName("Timu").Count;Debug.Log(XmlCount);//解析每一个题目for (int i = 0; i < XmlCount; i++){xmlData temp = new xmlData();XmlNodeList ls = XmlDoc.GetElementsByTagName("Timu")[i].ChildNodes;temp.key = ls[0].InnerText;temp.title = ls[1].InnerText;temp.q1 = ls[2].InnerText;temp.q2 = ls[3].InnerText;temp.q3 = ls[4].InnerText;temp.answer = ls[5].InnerText;//存储到题库xmls.Add(temp);}GetFiveQuestions();//foreach (var item in useArray)//{//    Debug.Log(item);//}}//判断问题是否正确public bool PanDuan(int topNumber, string answer){foreach (var item in useArray){if (useArray[topNumber].answer == answer){//Debug.Log("zhengque");return true;}else{//Debug.Log("cuowu");return false;}}return false;}/// <summary>/// 得到五道题/// </summary>public void GetFiveQuestions(){for (int i = 0; i < 5; i++){A1: int index = Random.Range(0, 15);if (xmlDatas.Add(xmls[index])){useArray.Add(xmls[index]);}else{goto A1;}}ResetTimu(topNumber);}/// <summary>/// 初始化题目/// </summary>/// <param name="index"></param>public void ResetTimu(int index){for (int i = 0; i < toggleList.Count; i++){toggleList[i].isOn = false;}for (int i = 0; i < DA_TextList.Count; i++){TM_Text.text = useArray[index].title;switch (i){case 0:DA_TextList[i].text = useArray[index].q1;break;case 1:DA_TextList[i].text = useArray[index].q2;break;case 2:DA_TextList[i].text = useArray[index].q3;break;}}}/// <summary>/// 确定之后进入下一题/// </summary>public void BtnClick(){//print(isSelect);if (topNumber == 4){Debug.Log("答完了");}if (isSelect == true){if (topNumber < 5){if (PanDuan(topNumber, selectAnswer)){topNumber++;if (topNumber<5){ResetTimu(topNumber);}isSelect = false;print("选择正确");}else{topNumber++;if (topNumber < 5){ResetTimu(topNumber);}isSelect = false;print("选择错误");}}else{return;}}else{return;}}}

改进版:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
using System.Xml;public class xmlres : MonoBehaviour
{[SerializeField]private List<Toggle> toggleList; // 答案ABC[SerializeField]private Text TM_Text; // 题目[SerializeField]private List<Text> DA_TextList; // 选项private int topNumber = 0;private string selectAnswer = " ";private bool isSelect = false; // 是否选中List<xmlData> xmls = new List<xmlData>();List<xmlData> useArray = new List<xmlData>();HashSet<xmlData> xmlDatas = new HashSet<xmlData>();public static xmlres instance;private void Awake(){instance = this;}void Start(){StartCoroutine(ReadQuestion());toggleList[0].onValueChanged.AddListener(OnValChanged0);toggleList[1].onValueChanged.AddListener(OnValChanged1);toggleList[2].onValueChanged.AddListener(OnValChanged2);}IEnumerator ReadQuestion(){string url = Path.Combine(Application.streamingAssetsPath, "myxml.xml");UnityWebRequest www = UnityWebRequest.Get(url);yield return www.SendWebRequest();if (www.isNetworkError || www.isHttpError){Debug.Log(www.error);}else{XmlDocument xmlDoc = new XmlDocument();xmlDoc.LoadXml(www.downloadHandler.text);int XmlCount = xmlDoc.GetElementsByTagName("Timu").Count;Debug.Log(XmlCount);for (int i = 0; i < XmlCount; i++){xmlData temp = new xmlData();XmlNodeList ls = xmlDoc.GetElementsByTagName("Timu")[i].ChildNodes;temp.key = ls[0].InnerText;temp.title = ls[1].InnerText;temp.q1 = ls[2].InnerText;temp.q2 = ls[3].InnerText;temp.q3 = ls[4].InnerText;temp.answer = ls[5].InnerText;xmls.Add(temp);}GetFiveQuestions();}}void OnValChanged0(bool check){if (check){selectAnswer = "A";isSelect = true;}}void OnValChanged1(bool check){if (check){selectAnswer = "B";isSelect = true;}}void OnValChanged2(bool check){if (check){selectAnswer = "C";isSelect = true;}}public bool PanDuan(int topNumber, string answer){if (useArray[topNumber].answer == answer){return true;}else{return false;}}public void GetFiveQuestions(){xmlDatas.Clear();useArray.Clear();while (useArray.Count < 5){int index = Random.Range(0, xmls.Count);if (xmlDatas.Add(xmls[index])){useArray.Add(xmls[index]);}}ResetTimu(topNumber);}public void ResetTimu(int index){TM_Text.text = useArray[index].title;DA_TextList[0].text = useArray[index].q1;DA_TextList[1].text = useArray[index].q2;DA_TextList[2].text = useArray[index].q3;foreach (var toggle in toggleList){toggle.isOn = false;}}public void BtnClick(){if (isSelect){bool correct = PanDuan(topNumber, selectAnswer);if (correct){Debug.Log("选择正确");}else{Debug.Log("选择错误");}topNumber++;if (topNumber < 5){ResetTimu(topNumber);}else{Debug.Log("答完了");}isSelect = false;}}
}public class xmlData
{public string key;public string title;public string q1;public string q2;public string q3;public string answer;
}

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • OpengGL教程(三)---使用VAO和VBO方式绘制三角形
  • python学习第九节:爬虫实战-抓取地址库
  • BMC+ssh和共享平台的Ironic服务,实现裸金属服务器的远程管理与调用
  • Java8 流的简单介绍
  • 如何防止ZIP压缩文件被随意打开?
  • 洞悉地下寒潮,守护温暖家园:智能CG-68冻土传感器监测系统
  • Windows 环境下 vscode 配置 C/C++ 环境
  • Vue3+setup实现父子组件单表增删改查写法模板
  • 掌握MATLAB中的数据类型转换技巧
  • java之认识异常
  • matlab绘制不同区域不同色彩的图,并显示数据(代码)
  • 【C++ 高频面试题】new、delete 与 malloc、free的区别
  • 64位系统中不支持In.vi与Out.vi的原因
  • 深入理解指针(二)
  • GD - GD32350R_EVAL - PWM实验和验证3 - EmbeddedBuilder - 无源蜂鸣器 - 用PMOS来控制
  • Android组件 - 收藏集 - 掘金
  • CentOS学习笔记 - 12. Nginx搭建Centos7.5远程repo
  • Map集合、散列表、红黑树介绍
  • Nginx 通过 Lua + Redis 实现动态封禁 IP
  • sublime配置文件
  • Webpack 4x 之路 ( 四 )
  • 分类模型——Logistics Regression
  • 基于阿里云移动推送的移动应用推送模式最佳实践
  • 手机端车牌号码键盘的vue组件
  • 数组的操作
  • 通过几道题目学习二叉搜索树
  • 运行时添加log4j2的appender
  • Spark2.4.0源码分析之WorldCount 默认shuffling并行度为200(九) ...
  • ​数据链路层——流量控制可靠传输机制 ​
  • ‌‌雅诗兰黛、‌‌兰蔻等美妆大品牌的营销策略是什么?
  • #Z0458. 树的中心2
  • $jQuery 重写Alert样式方法
  • (07)Hive——窗口函数详解
  • (13)DroneCAN 适配器节点(一)
  • (C11) 泛型表达式
  • (pojstep1.1.2)2654(直叙式模拟)
  • (顶刊)一个基于分类代理模型的超多目标优化算法
  • (二)pulsar安装在独立的docker中,python测试
  • (仿QQ聊天消息列表加载)wp7 listbox 列表项逐一加载的一种实现方式,以及加入渐显动画...
  • (附源码)springboot 智能停车场系统 毕业设计065415
  • (附源码)计算机毕业设计ssm-Java网名推荐系统
  • (附源码)计算机毕业设计ssm电影分享网站
  • (强烈推荐)移动端音视频从零到上手(下)
  • (十)c52学习之旅-定时器实验
  • (一)基于IDEA的JAVA基础1
  • (转)关于pipe()的详细解析
  • (转载)在C#用WM_COPYDATA消息来实现两个进程之间传递数据
  • (轉貼) 2008 Altera 亞洲創新大賽 台灣學生成果傲視全球 [照片花絮] (SOC) (News)
  • *Django中的Ajax 纯js的书写样式1
  • .gitignore不生效的解决方案
  • .Net Core 笔试1
  • .Net Core 中间件验签
  • .NET 程序如何获取图片的宽高(框架自带多种方法的不同性能)
  • .NET/C#⾯试题汇总系列:⾯向对象
  • .pub是什么文件_Rust 模块和文件 - 「译」