Мой JSON писатель пишет только один объект из моей симуляции? - PullRequest
0 голосов
/ 23 апреля 2020

Я пытаюсь получить функцию WriteData () для сохранения информации о нескольких объектах сцены в формате JSON. Однако проблема, с которой я сталкиваюсь, заключается в том, что мой писатель сохраняет только начальные координаты одной ячейки, которая составляет мой пол, а не сохраняет все координаты пола.

В настоящее время у меня есть префабы с тегами, которые я нахожу и сохраняю в массиве игрового объекта. Затем, используя foreach l oop - go через каждый массив игровых объектов, чтобы получить соответствующую информацию для присвоения ее данным в созданном мной сериализуемом классе, затем добавьте его в файл JSON. В этом процессе он также сохраняет данные в виде отдельных JSON строк, а не объединенной строки.

Я впервые использую JSON / Unity's JSON Utility, поэтому любая помощь будет признателен.

Ниже приведены соответствующие части моего сценария, которые я сейчас использую для этого.

using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEngine;

public class GameManager : MonoBehaviour
{

    //used to calculate the rate at which data is collected and written to file
    public float sampleRate = 1f;

    //name of the file when writing data
    string fileName;

    SaveData saveData;      //save data class object 

    //fields for retrieving the data about dynamic humans in the scene
    GameObject[] dynamicHumanTarget;
    string newDynamicHumanId;
    Vector3 newDynamicHumanPosition = new Vector3();
    Vector3 newDynamicHumanRotation = new Vector3();

    //fields for retrieving the data about static humans in the scene;
    GameObject[] staticHumanTarget;
    string newStaticHumanId;
    Vector3 newStaticHumanPosition = new Vector3();
    Vector3 newStaticHumanRotation = new Vector3();

    //fields for retrieving the data about static humans in the scene;
    GameObject[] staticObjectTarget;
    string newStaticObjectId;
    Vector3 newStaticObjectPosition = new Vector3();
    Vector3 newStaticObjectRotation = new Vector3();

    //fields for retrieving the data about the target in the scene;
    GameObject[] targets;
    string newTargetId;
    Vector3 newTargetPosition = new Vector3();
    Vector3 newTargetRotation = new Vector3();

    //fields for retrieving the data about the target in the scene;
    GameObject[] rooms;
    //string newWallId;
    IntVector2 newRoomCoordinates = new IntVector2();



    //called before the simulation is executed
    void Start()
    {
        fileName = "/SimulationData_" + System.DateTime.Now.ToString("dd-MM-yyyy_hh-mm-ss") + ".json";
        saveData = new SaveData();

        dynamicHumanTarget = GameObject.FindGameObjectsWithTag("DynamicHuman");
        staticHumanTarget = GameObject.FindGameObjectsWithTag("StaticHuman");
        staticObjectTarget = GameObject.FindGameObjectsWithTag("StaticObject");
        targets = GameObject.FindGameObjectsWithTag("Target");
        rooms = GameObject.FindGameObjectsWithTag("Cell");
    }

    //called to update the simulation 
    void Update()
    {
        GetDynamicHumanData();
        GetStaticHumanData();
        GetStaticObjectData();
        GetTargetData();
        GetWallData();
        StartWriter();
    }

    public void WriteData()
    {
        string path = Application.persistentDataPath + fileName;
        if (!File.Exists(path))
        {
            File.WriteAllText(path, "");
        }

        //robot
        saveData.robotID = robotInstance.robotID;
        saveData.robotPosition = robotInstance.transform.position;
        saveData.robotRotation = robotInstance.transform.eulerAngles;

        //dynamic humans
        saveData.dynamicHumanId = newDynamicHumanId;
        saveData.dynamicHumanPosition = newDynamicHumanPosition;
        saveData.dynamicHumanRotation = newDynamicHumanRotation;

        ///static humans
        saveData.staticHumanId = newStaticHumanId;
        saveData.staticHumanPosition = newStaticHumanPosition;
        saveData.staticHumanRotation = newStaticHumanRotation;

        //static objects
        saveData.staticObjectId = newStaticObjectId;
        saveData.staticObjectPosition = newStaticObjectPosition;
        saveData.staticObjectRotation = newStaticObjectRotation;

        //room objects
        saveData.roomCoordinates = newRoomCoordinates;


        string json = JsonUtility.ToJson(saveData);
        Debug.Log(json);
        File.AppendAllText(path, json);
    }

    void GetWallData()
    {
        foreach (GameObject room in rooms)
        {
            // newWallId = room.GetComponent<MazeWall>().id;
            newRoomCoordinates = room.GetComponent<MazeCell>().coordinates;
        }
    }

    void GetTargetData()
    {
        foreach (GameObject target in targets)
        {
            newTargetId = target.GetComponent<Target>().id;
            newTargetPosition = target.transform.position;
            newTargetRotation = target.transform.eulerAngles;
        }

    }


    void GetStaticObjectData()
    {
        foreach (GameObject staticObject in staticObjectTarget)
        {
            newStaticObjectId = staticObject.GetComponent<StaticObject>().id;
            newStaticObjectPosition = staticObject.transform.position;
            newStaticObjectRotation = staticObject.transform.eulerAngles;
        }
    }


    void GetStaticHumanData()
    {
        foreach (GameObject staticHuman in staticHumanTarget)
        {
            newStaticHumanId = staticHuman.GetComponent<StaticHuman>().id;
            newStaticHumanPosition = staticHuman.transform.position;
            newStaticHumanRotation = staticHuman.transform.eulerAngles;
        }
    }


    void GetDynamicHumanData()
    {
        foreach (GameObject dynamicHuman in dynamicHumanTarget)
        {
            newDynamicHumanId = dynamicHuman.GetComponent<DynamicHuman>().id;
            newDynamicHumanPosition = dynamicHuman.transform.position;
            newDynamicHumanRotation = dynamicHuman.transform.eulerAngles;

        }
    }

    //start the data writer and repeatedly invoke it based on the sample rate
    public void StartWriter()
    {
        InvokeRepeating("WriteData", 0, 1 / sampleRate);
    }

    //stops the data writer
    public void StopWriter()
    {
        CancelInvoke();
    }
}
    [System.Serializable]
    public class SaveData
    {
        //room positions       
        public IntVector2 roomCoordinates;

        //target position
        public string targetId;
        public Vector3 targetPosition;
        public Vector3 targetRotation;

        //static objects e.g chairs
        public string staticObjectId;
        public Vector3 staticObjectPosition;
        public Vector3 staticObjectRotation;

        //static humans
        public string staticHumanId;
        public Vector3 staticHumanPosition;
        public Vector3 staticHumanRotation;


        //dynamic humans
        public string dynamicHumanId;
        public Vector3 dynamicHumanPosition;
        public Vector3 dynamicHumanRotation;


        //robot data
        public string robotID;
        public Vector3 robotPosition;
        public Vector3 robotRotation;

    }

Пример фрагмента моего JSON файла:

{
    "roomCoordinates": {
        "x": 2,
        "z": 2
    },
    "targetId": "",
    "targetPosition": {
        "x": 0.0,
        "y": 0.0,
        "z": 0.0
    },
    "targetRotation": {
        "x": 0.0,
        "y": 0.0,
        "z": 0.0
    },
    "staticObjectId": "Chair",
    "staticObjectPosition": {
        "x": 0.5,
        "y": 0.0,
        "z": 1.5
    },
    "staticObjectRotation": {
        "x": 0.0,
        "y": 0.0,
        "z": 0.0
    },
    "staticHumanId": "StaticHuman",
    "staticHumanPosition": {
        "x": -1.5,
        "y": 0.0,
        "z": -4.5
    },
    "staticHumanRotation": {
        "x": 0.0,
        "y": 0.0,
        "z": 0.0
    },
    "dynamicHumanId": "DynamicHuman",
    "dynamicHumanPosition": {
        "x": -1.149653673171997,
        "y": 0.10249999165534973,
        "z": 3.8513429164886476
    },
    "dynamicHumanRotation": {
        "x": 0.0,
        "y": 40.97020721435547,
        "z": 0.0
    },
    "robotID": "Robot",
    "robotPosition": {
        "x": 2.5047712326049806,
        "y": 0.07088841497898102,
        "z": -3.4777321815490724
    },
    "robotRotation": {
        "x": 359.7475891113281,
        "y": 359.37066650390627,
        "z": -0.003071203362196684
    }
}{
    "roomCoordinates": {
        "x": 2,
        "z": 2
    },
    "targetId": "",
    "targetPosition": {
        "x": 0.0,
        "y": 0.0,
        "z": 0.0
    },
    "targetRotation": {
        "x": 0.0,
        "y": 0.0,
        "z": 0.0
    },
    "staticObjectId": "Chair",
    "staticObjectPosition": {
        "x": 0.5,
        "y": 0.0,
        "z": 1.5
    },
    "staticObjectRotation": {
        "x": 0.0,
        "y": 0.0,
        "z": 0.0
    },
    "staticHumanId": "StaticHuman",
    "staticHumanPosition": {
        "x": -1.5,
        "y": 0.0,
        "z": -4.5
    },
    "staticHumanRotation": {
        "x": 0.0,
        "y": 0.0,
        "z": 0.0
    },
    "dynamicHumanId": "DynamicHuman",
    "dynamicHumanPosition": {
        "x": -0.9079896807670593,
        "y": 0.1025000512599945,
        "z": 4.286510944366455
    },
    "dynamicHumanRotation": {
        "x": 0.0,
        "y": 20.490304946899415,
        "z": 0.0
    },
    "robotID": "Robot",
    "robotPosition": {
        "x": 2.4922380447387697,
        "y": 0.07088327407836914,
        "z": -3.2451395988464357
    },
    "robotRotation": {
        "x": 359.7496032714844,
        "y": 357.0594177246094,
        "z": 359.7879638671875
    }
}

1 Ответ

0 голосов
/ 23 апреля 2020

Благодаря подсказке BugFinder вам нужно обернуть массивы, поскольку утилита json не поддерживает массивы, см. Это:

https://answers.unity.com/questions/1123326/jsonutility-array-not-supported.html

Таким образом, вы можете l oop через своих людей, роботов, цели, объекты и т. Д. c, добавить их в массив, а затем обернуть массив в свой объект SaveData. Больше информации;

https://forum.unity.com/threads/json-utility-save-and-load-a-list.488263/#post -3185216

...