文章目录
- 需求:
- Json文件存在服务器上,Unity要获取并解析它。
- 原理:
- 通过`UnityWebRequest类获取服务器文本`的功能,把Json文件传输到本地。
- 再通过写好的解析类、Unity自带的JsonUtility.FromJson()解析方法,得到所需变量的值。
- 实现:
- 一、“UnityWebRequest类获取服务器文本”功能
- 二、根据Json文件内容,写解析类
- 三、用Unity自带的JsonUtility.FromJson()解析方法,得到所需变量的值
- 四、加在游戏物体上的完整代码+打印出的语句
- 注意:
需求:
原理:
通过UnityWebRequest类获取服务器文本
的功能,把Json文件传输到本地。
实现:
一、“UnityWebRequest类获取服务器文本”功能
官方的代码
using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
public class MyBehaviour : MonoBehaviour {
void Start() {
StartCoroutine(GetText());
}
IEnumerator GetText() {
UnityWebRequest www = UnityWebRequest.Get("https://www.my-server.com");
yield return www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success) {
Debug.Log(www.error);
}
else {
// 以文本形式显示结果
Debug.Log(www.downloadHandler.text);
// 或者获取二进制数据形式的结果
//这句代码,用不到,就删除,不要了
byte[] results = www.downloadHandler.data;
}
}
}
我代码里,这部分的截图
二、根据Json文件内容,写解析类
Json文件内容:
{
“picInfoArray”:[{“url”:“adr1”},{“url”:“adr2”},{“url”:“adr3”}]
}
它由两个类组成:外部的类,有一个叫“picInfoArray”的数组变量;内部的类,有一个叫url的字符串变量
我代码里,这部分的截图
三、用Unity自带的JsonUtility.FromJson()解析方法,得到所需变量的值
我代码里,这部分的截图图中绿色Step1、Step2、Step3,及相应红线部分
四、加在游戏物体上的完整代码+打印出的语句
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using System;
[Serializable]
public class PicInfo
{
public string url;
//public int posNum;
public PicInfo(string url)//, int posNum)
{
this.url = url;
//this.posNum = posNum;
}
}
[Serializable]
public class PicInfoCollection
{
public PicInfo[] picInfoArray;
}
public class GetJsonFromServer : MonoBehaviour
{
private string jsonFileFromServer;
// Start is called before the first frame update
void Start()
{
StartCoroutine(GetText());
}
IEnumerator GetText()
{
UnityWebRequest www = UnityWebRequest.Get("http://47.96.106.49/filetest/SelfWriteJson.json");
yield return www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success)
{
Debug.Log("传递不成功" + www.error);
}
else
{
//Step1:获取到网络“服务器端”Json文件
jsonFileFromServer = www.downloadHandler.text;
Debug.Log("Step1:" + jsonFileFromServer);
//Step2:解析获得:外层较大的类,的对象
PicInfoCollection picInfoCollection = JsonUtility.FromJson<PicInfoCollection>(jsonFileFromServer);
Debug.Log("Step2:" + picInfoCollection.picInfoArray);
//Step3:由大类的对象,打印:内层较小类对象的变量
foreach (PicInfo picUrl in picInfoCollection.picInfoArray)
{
Debug.Log("Step3:" + picUrl.url);
}
}
}
}
注意:
此处得到的变量对象:url地址,是字符串形式,它是有引号的——有些地方用的时候,要把引号去掉。
我的处理如下——把引号用空来替换:
注意,Replace第一个参数,直接写引号不管用,得用转义字符反斜杠,转一下