JsonUtility 工作得更早,但在 VS 中编译后,我认为它停止了
JsonUtility worked earlier but after a compile in VS, it stopped i think
Untiies JsonUtility class 创建一个对象,但不设置它的变量。
我确定代码是正确的,因为它在今天早些时候运行。还 tjeked 指南。
public class Player
{
public int speed;
public int health;
public int x;
public int y;
}
public class Testing : MonoBehaviour
{
[SerializeField] private TextAsset _textAsset;
void Start()
{
Player p = JsonUtility.FromJson<Player>(_textAsset.text);
Debug.Log(p.speed); // should print 5
}
}
{
"player": {
"speed": 5,
"health": 3,
"x": 0,
"y": -4
}
}
今天早些时候上面的方法起作用了,我不确定是什么让它停止了。并输入了正确的文本资产文件。
我认为它坏了。进入 Visual Studio 并编译一次。
我尝试制作一个新项目,但没有成功。
资产位于 Unity 包中。以下 link 将在 7 天后过期。
https://easyupload.io/dkmrnd
您 JSON 中的结构不是您的代码所期望的结构。
首先是的,你的播放器 class 需要
[Serializable]
public class Player
{
// fields here NO properties!
}
但是,你的JSON嵌套的更深了!
要么只需要
{
"speed": 5,
"health": 3,
"x": 0,
"y": -4
}
或者您需要一个相应的包装器 class
[Serializable]
public class JsonRoot
{
public Player player;
}
然后你需要做
Player p = JsonUtility.FromJson<JsonRoot>(_textAsset.text).player;
Untiies JsonUtility class 创建一个对象,但不设置它的变量。
我确定代码是正确的,因为它在今天早些时候运行。还 tjeked 指南。
public class Player
{
public int speed;
public int health;
public int x;
public int y;
}
public class Testing : MonoBehaviour
{
[SerializeField] private TextAsset _textAsset;
void Start()
{
Player p = JsonUtility.FromJson<Player>(_textAsset.text);
Debug.Log(p.speed); // should print 5
}
}
{
"player": {
"speed": 5,
"health": 3,
"x": 0,
"y": -4
}
}
今天早些时候上面的方法起作用了,我不确定是什么让它停止了。并输入了正确的文本资产文件。
我认为它坏了。进入 Visual Studio 并编译一次。
我尝试制作一个新项目,但没有成功。
资产位于 Unity 包中。以下 link 将在 7 天后过期。 https://easyupload.io/dkmrnd
您 JSON 中的结构不是您的代码所期望的结构。
首先是的,你的播放器 class 需要
[Serializable]
public class Player
{
// fields here NO properties!
}
但是,你的JSON嵌套的更深了!
要么只需要
{
"speed": 5,
"health": 3,
"x": 0,
"y": -4
}
或者您需要一个相应的包装器 class
[Serializable]
public class JsonRoot
{
public Player player;
}
然后你需要做
Player p = JsonUtility.FromJson<JsonRoot>(_textAsset.text).player;