1. Got the question bank
Analyze what can be defined
1. Serial number, used to distinguish the number of questions. Each question has a unique serial number.
2. The question is Q in the picture below
3. Default answer , A in the picture below
After analysis, I can know that there are three fields, namely int index, string Q, and string A.
2. Throw the fields into the Excel table
Write the fields in the first line, and then write the data below.
3. Convert Excel into Json files through some tools
You can see that the generated Json file looks like this
It looks a little messy, you can use the formatting tool to adjust it.
This is my commonly used formatting tool
In this way, our questions and preset answers can be clearly distinguished, and some small adjustments can also be processed directly here.
4. Change the Json file
Create a new txt text, paste all the data just generated into the text, and change the suffix to .json
This is a qualified Json file
5. Generate C# class
Still on the website just now, find the Json to C# entity class, throw your Json file into it and it will generate a C# class for you.
Create a new QAData class in Unity and copy the generated ones (the generated ones are usually Root, change them to your own classes).
6. Json parsing
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Networking;
public class Test : MonoBehaviour
{
void Start()
{
StartCoroutine(LoadJson(Application.streamingAssetsPath + "/QA.json",JsonHandle));
}
/// <summary>
/// 处理Json数据
/// </summary>
void JsonHandle(string jsonData)
{
Debug.Log(jsonData);
QAData qAData = JsonConvert.DeserializeObject<QAData>(jsonData);
Debug.Log(" 共有" + qAData.QA.Count + "题");
foreach (var item in qAData.QA)
{
Debug.Log(item.index);
Debug.Log(item.Q);
Debug.Log(item.A);
}
}
/// <summary>
/// 读取Json数据
/// </summary>
/// <param name="path"></param>
/// <param name="action"></param>
/// <returns></returns>
IEnumerator LoadJson(string path,UnityAction<string> action = null)
{
// 提取Json文件
UnityWebRequest www = UnityWebRequest.Get(path);
yield return www.SendWebRequest();
if (www.result == UnityWebRequest.Result.Success)
{
string jsonString = www.downloadHandler.text;
action?.Invoke(jsonString);
}
else
{
Debug.Log("读取失败");
}
}
}
In this way, everything is dismantled, and the question-answering system follows the same idea.
The advantage of this is that when you need to modify the question bank externally, you don’t need to repackage it, just change the Json file directly.