unity json读取
时间: 2023-10-18 13:59:13 浏览: 159
在Unity中,你可以使用JsonUtility类来读取和解析JSON数据。下面是一个简单的示例代码,演示如何使用JsonUtility来读取JSON数据并将其转化为对象:
```csharp
using UnityEngine;
using System.IO;
public class JSONReader : MonoBehaviour
{
void Start()
{
// 读取JSON文件
string jsonFilePath = Application.streamingAssetsPath + "/data.json";
string jsonData = File.ReadAllText(jsonFilePath);
// 将JSON数据转化为对象
MyDataObject dataObject = JsonUtility.FromJson<MyDataObject>(jsonData);
// 在控制台输出对象的属性
Debug.Log("Name: " + dataObject.name);
Debug.Log("Age: " + dataObject.age);
Debug.Log("Score: " + dataObject.score);
}
}
[System.Serializable]
public class MyDataObject
{
public string name;
public int age;
public float score;
}
```
在上面的示例中,我们首先使用`File.ReadAllText`方法从JSON文件中读取数据。然后,使用`JsonUtility.FromJson`方法将JSON数据转化为`MyDataObject`对象。最后,我们可以通过访问对象的属性来获取JSON数据中的值。
请注意,为了使对象与JSON数据匹配,我们使用了`[System.Serializable]`特性来标记`MyDataObject`类。
确保将上述脚本附加到场景中的某个游戏对象上,并创建一个名为"data.json"的JSON文件,并将其放置在Unity的StreamingAssets文件夹下。这样,当你运行游戏时,脚本将读取该JSON文件并输出数据。
希望能对你有所帮助!如果你有任何其他问题,请随时提问。
阅读全文
相关推荐


















