如何从Json加载Gameobject?可以吗?

时间:2019-03-29 13:32:13

标签: c# ios unity3d

我正在尝试保存对象的位置,旋转和缩放。此外,我还可以将Gameobject本身保存在json中。我将JSON文件保存在Application.persistentDataPath中。下面是我的datahandler类

  using System;
  using UnityEngine;

[Serializable]
public class DataHandlers

{
public Vector3 localposinmap;
public Quaternion localrotinmap;
public Vector3 sizeofobj;
public GameObject gameobj;

public DataHandlers(Vector3 localpos, Quaternion localrot, Vector3 objsize,GameObject gobj)

{
    this.localposinmap = localpos;
    this.localrotinmap = localrot;
    this.sizeofobj = objsize;
    this.gameobj = gobj;

}


}

保存文件后,我的JSON字符串如下

{

"SaveValues": [
{
  "localposinmap": {
    "x": 0.0237075537443161,
    "y": -0.27374106645584106,
    "z": -0.6681503057479858
  },
  "localrotinmap": {
    "x": 0,
    "y": -0.08031735569238663,
    "z": 0,
    "w": -0.996769368648529
  },
  "sizeofobj": {
    "x": 1,
    "y": 1,
    "z": 1
  },
  "gameobj": {
    "m_FileID": -112,
    "m_PathID": 0
  }
},
{
  "localposinmap": {
    "x": 0.09054452180862427,
    "y": -0.273919016122818,
    "z": -0.5062751770019531
  },
  "localrotinmap": {
    "x": 0.0001220703125,
    "y": 0.06480370461940765,
    "z": 0,
    "w": -0.9978980422019958
  },
  "sizeofobj": {
    "x": 1,
    "y": 1,
    "z": 1
  },
  "gameobj": {
    "m_FileID": -456,
    "m_PathID": 0
  }
}
 ]
}

阅读gameobj之后:“ m_FileID”:-456和“ m_PathID”:0 我可以使用上述详细信息读回该值并实例化同一个Gameobject吗?

1 个答案:

答案 0 :(得分:1)

您可以使用JsonUtility.ToJson将对象更改为json字符串,并使用JsonUtility.FromJson将其恢复。检查Unity docs了解更多信息。请记住:

  

仅支持简单的类和结构;不是从UnityEngine.Object派生的类(例如MonoBehaviour或ScriptableObject)。