Surya
Surya

Reputation: 19

Saving a 2D array as JSON

I Have problem to save my simulation into JSON File. the basics I make a moving ship. in the world space there will be a probe button that will provide information about the ship. I want to save that information into JSON. Anyone know how to do that. I am new in Unity. In button () I want to save the ship information (eg. position, depthsea, windspeed, temperature,flow

public class test : MonoBehaviour
{
    // Start is called before the first frame update

    public GameObject Ship;
    public GameObject hole;
    public GameObject turtle;
    public GameObject panelhole;
    public GameObject panelturtle;
    
    public RectTransform shipvalue;
    //public RectTransform flowvalue;
    //public RectTransform windspeedvalue;
    //public RectTransform temperaturevalue;
    //public RectTransform depthvalue;
    public Vector3 offset;
    public RectTransform Basicobject; //parent



    //public static bool captureAllKeyboardInput = false;

    private bool paneloff = false;
    public float duration = 1;

    public int[,] grid = new int[10, 16];
    public float[,] depth = new float[4, 3]
    {{1.6f, 2.3f, 3.5f },
     {4, 5, 6.5f},
     {7, 8, 6.5f},
     {7, 8, 6.5f}};
 
    public float[,] temperaturedata = new float[10, 16]
    {{0,    0,      0,      0,      0,      0,      0,      22.5f,  22.7f,  23,     23.9f,  24,     26.3f,  26.4f,  26.4f,  26.3f},
    {0,     0,      0,      0,      0,      0,      22.8f,  23.2f,  23.8f,  24.4f,  25,     24.3f,  26.5f,  26.5f,  26.5f,  26.6f},
    {0,     0,      0,      0,      0,      22.5f,  23.1f,  24.8f,  25.3f,  25.7f,  0,      0,      26.7f,  26.3f,  26.2f,  26.6f},
    {0,     0,      0,      0,      23.2f,  23.8f,  25.1f,  25.4f,  25.9f,  0,      0,      26.8f,  26.9f,  26.5f,  26.3f,  26.3f},
    {0,     0,      24.5f,  23.3f,  23.9f,  24.5f,  25.7f,  25.6f,  26.8f,  0,      0,      26.9f,  27.1f,  26.6f,  26.4f,  26.4f},
    {0,     24.1f,  23.9f,  24.9f,  25.4f,  25.5f,  25.9f,  27.4f,  27.2f,  0,      0,      27,     27.2f,  26.8f,  26.4f,  26   },
    {27.4f, 27.7f,  27.3f,  26.2f,  26.2f,  25.9f,  27.5f,  27.7f,  27.3f,  0,      26.8f,  27.2f,  27.2f,  26.9f,  26.4f,  26.2f},
    {28.5f, 29,     27.5f,  27.3f,  27.3f,  27.5f,  27.7f,  27.7f,  27.5f,  27.2f,  27.2f,  27.4f,  27.4f,  26.9f,  26.3f,  26.7f},
    {28.5f, 27.6f,  27.1f,  27,     26.5f,  27.6f,  27.6f,  27.6f,  27.7f,  27.4f,  27.8f,  27.7f,  27.7f,  27,     27,     26.6f},
    {28.5f, 27.6f,  25,     27.3f,  26.8f,  27.8f,  27.3f,  27.5f,  28.1f,  27.9f,  28,     27.6f,  27.7f,  26.9f,  27.1f,  26.8f}};


    public float[,] flowdata = new float[10, 16]
 
    {{0,    0,      0,      0,      0,      0,      0,      0.4f,   0.4f,   0.6f,   0.8f,   0.6f,   0.7f,   0.4f,   0.4f,   0.4f},
    {0,     0,      0,      0,      0,      0,      0.3f,   0.5f,   0.5f,   0.8f,   0.8f,   0.8f,   0.6f,   0.6f,   0.5f,   0.5f},
    {0,     0,      0,      0,      0,      0.4f,   0.7f,   0.7f,   0.7f,   0.7f,   0,      0,      0.9f,   0.6f,   0.4f,   0.4f},
    {0,     0,      0,      0,      0.5f,   0.5f,   0.6f,   0.7f,   0.6f,   0,      0,      0.8f,   0.8f,   0.4f,   0.3f,   0.3f},
    {0,     0,      000,    0.7f,   0.6f,   0.5f,   0.7f,   1,      0.8f,   0,      0,      0.9f,   0.5f,   0.3f,   0.1f,   0.3f},
    {0,     0.5f,   0.7f,   0.6f,   0.8f,   0.8f,   1.3f,   0.9f,   0.5f,   0,      0,      0.8f,   0.3f,   0.1f,   0.2f,   0.2f},
    {0.6f,  0.6f,   0.6f,   0.7f,   1.1f,   0.9f,   0.8f,   0.4f,   0.3f,   0,      0.9f,   0.6f,   0.2f,   0.2f,   0.2f,   0.2f},
    {0.4f,  0.4f,   0.5f,   0.5f,   0.3f,   0.4f,   0.3f,   0.2f,   0.4f,   0.2f,   0.8f,   0.3f,   0.2f,   0.2f,   0.2f,   0.1f},
    {000,   0.3f,   0.5f,   0.2f,   0.2f,   0.2f,   0.2f,   0.1f,   0.2f,   0.6f,   0.6f,   0.3f,   0.3f,   0.2f,   0.2f,   0.2f},
    {000,   000,    0.1f,   0.4f,   0.3f,   0.3f,   0.2f,   0.2f,   0.1f,   0.2f,   0.3f,   0.1f,   0.2f,   0.2f,   0.2f,   0.2f}};

    public float[,] windspeeddata = new float[10, 12]
    {{0,0,0,0,0,0,0,4,4,4,3,3},
    {0,0,0,0,0,0,4,5,4,3,3,3},
    {0,0,0,0,0,5,5,5,5,3,0,0},
    {0,0,0,0,4,4,4,4,4,0,0,3},
    {0,0,3,0,4,4,4,4,4,0,0,3},
    {0,4,4,4,4,4,4,4,3,0,0,3},
    {4,4,4,4,4,4,4,3,3,0,3,4},
    {5,4,4,4,4,4,3,3,3,3,4,4},
    {4,4,4,4,4,4,3,3,3,3,4,4},
    {5,4,4,4,4,4,4,4,4,3,3,3}};


    int row, column, num1, num2;
    int p1;
    int p2;

    int[] grid2 = new int[5];
    public Text shiposition = null;
    public Text depthtext = null;
    public Text windspeedtext = null;
    public Text temperaturetext = null;
    public Text flowtext = null;

    //direction = Ship.transform.rotation.z;
    float LastMove;
    float timeIn = 0.5f;
    public Vector3 direction;

    float zvalue;

    [Serializable]
    public class ShipData
    {

        public int grid;
        public float depth;
        public float windspeed;
        public float temperature;

    }

    [SerializeField]
    private ShipData JSON_ShipData = new ShipData();

    public void SaveintoJson()
    {
        string data = JsonUtility.ToJson(JSON_ShipData);
        System.IO.File.WriteAllText(Application.persistentDataPath + "/DataCenter.json", data);
        Debug.Log("Saving as JSON" + JSON_ShipData);
        Debug.Log(Application.persistentDataPath);
    }

    void Start()
    {
        p1 = 9;
        p2 = 0;
        
        grid[p1, p2] = 1;
        panelhole.SetActive(false);
        panelturtle.SetActive(false);
        Debug.Log(grid[p1, p2]);
        Debug.Log(shiposition.transform.position);
       
    }
    // Update is called once per frame




    void Update()
    {
        
        //Debug.Log(Ship.transform.localEulerAngles.z);
        zvalue = Ship.transform.localEulerAngles.z;

        if (Input.GetKeyDown(KeyCode.RightArrow))
        {

            StartCoroutine(Forward());
       }
        if (Input.GetKeyDown(KeyCode.LeftArrow))
        {
            StartCoroutine(Backward());
        }
        if (Input.GetKeyDown(KeyCode.DownArrow))
        {
            StartCoroutine(Rotate(Vector3.forward, -90, 1.0f));
            Debug.Log(transform.rotation.eulerAngles.z);
        }
       if (Input.GetKeyDown(KeyCode.UpArrow))
        {
            StartCoroutine(Rotate(Vector3.forward, 90, 1.0f));
            Debug.Log(transform.rotation.eulerAngles.z);
        }
         

        if (Time.time - LastMove > timeIn)
        {
            LastMove = Time.time;
           
        }

        if (Input.GetKeyDown(KeyCode.W))
        {
            
                StartCoroutine(Rotate(Vector3.forward, 90, 1.0f));
               // position(grid);
               // depthsea(depth);
           
        }
        if (Input.GetKeyDown(KeyCode.A))
        {
            if (p2 >= 0)
            {
                StartCoroutine(Backward());
                grid[p1, p2] = 0;
                grid[p1, --p2] = 1;
                //position(grid);
                //depthsea(depth);
            }
            else
            {
                Debug.Log("You can't move left!!");
            }
        }
        if (Input.GetKeyDown(KeyCode.D))
        {
            
            // z = 0
            if (p2 <= 12 && zvalue == 0)
            {
                StartCoroutine(Forward());
                grid[p1, p2] = 0;
                grid[p1, ++p2] = 1;
                //position(grid);
                //depthsea(depth);
                Debug.Log(zvalue);
            }
            // z = 270
            else if (p2 <= 12 && zvalue == 270)
            {
                StartCoroutine(Forward());
                grid[p1, p2] = 0;
                grid[++p1, p2] = 1;
               // position(grid);
                //depthsea(depth);
                Debug.Log(zvalue);
            }

            //// z = 180
            else if (p2 <= 12 && zvalue == 180)
            {
                StartCoroutine(Forward());
                grid[p1, p2] = 0;
                grid[p1, --p2] = 1;
               // position(grid);
                //depthsea(depth);
                Debug.Log(zvalue);
            }
            //// z = 90
            else if (p2 <= 12 && zvalue == 90)
            {
                StartCoroutine(Forward());
                grid[p1, p2] = 0;
                grid[--p1, p2] = 1;
               // position(grid);
                //depthsea(depth);
                Debug.Log(zvalue);
            }
            else
            {
                Debug.Log("You can't move right any further!!");
                Debug.Log(Ship.transform.localEulerAngles.z);
            }
        }
        if (Input.GetKeyDown(KeyCode.S))
        {
           
                StartCoroutine(Rotate(Vector3.forward, -90, 1.0f));
                //position(grid);
                //depthsea(depth);
           
        }
        //WebGLInput.captureAllKeyboardInput = false;
    }

    
    private void position(int[,] grid)
    {

        for (int i = 0; i < grid.GetLength(0); i++)
        {
            for (int j = 0; j < grid.GetLength(1); j++)
            {
                if (grid[i, j] == 1)
                {
                   // Debug.Log("x: " + i + " y: " + j + " Grid: " + grid[i, j]);
                   
                    shiposition.text = "X : " + i + " " + "Y : " + j;
                    shiposition.text.ToString();
                    PlayerPrefs.SetString("position", shiposition.text);
                    PlayerPrefs.Save();
                    Debug.Log(shiposition.text);
                    
                }

            }
        }
    }

    public void windspeed(float[,] windspeeddata)
    {
        for (int x = 0; x < windspeeddata.GetLength(0); x++)
        {
            for (int y = 0; y < windspeeddata.GetLength(1); y++)
            {
                if (grid[x, y] == 1)
                {

                    windspeedtext.text = "Windspeed Level :" + windspeeddata[x, y];
                   
                }

            }
        }

    }


    public void temperature(float[,] temperaturedata)
    {
        for (int x = 0; x < temperaturedata.GetLength(0); x++)
        {
            for (int y = 0; y < temperaturedata.GetLength(1); y++)
            {
                if (grid[x, y] == 1)
                {
                    //Debug.Log(temperaturedata[x, y]);
                    temperaturetext.text = "Temperature :" + temperaturedata[x, y] + "C";
                }

            }
        }
    }

    public void flow(float[,] flowdata)
    {
        for (int x = 0; x < flowdata.GetLength(0); x++)
        {
            for (int y = 0; y < flowdata.GetLength(1); y++)
            {
                if (grid[x, y] == 1)
                {

                    flowtext.text = "Flow :" + flowdata[x, y];
                }

            }
        }
    }

    public void depthsea(float[,] depth)
    {
        for (int x = 0; x < depth.GetLength(0); x++)
        {
            for (int y = 0; y < depth.GetLength(1); y++)
            {
                if (grid[x, y] == 1)
                {
                    depthtext.text = "Depth :" + depth[x, y];
                    Debug.Log(depth[x, y]);
                }
       
            }
        }
    }

    public void moveobject()
    {
        
        shipvalue.transform.position = Ship.transform.position;
        //shipvalue.transform.position.y + 0.5f;
        //flowvalue.transform.position = Ship.transform.position;
        //windspeedvalue.transform.position = Ship.transform.position;
        //temperaturevalue.transform.position = Ship.transform.position;
        //depthvalue.transform.position = Ship.transform.position;

    }
    
    public void button()
    {
        
        position(grid);
        depthsea(depth);
        windspeed(windspeeddata);
        temperature(temperaturedata);
        flow(flowdata);
        moveobject();
     

        //value.transform.position = Ship.transform.position;
        //string newposition = JsonUtility.ToJson(shiposition.text);
        //System.IO.File.WriteAllText(Application.persistentDataPath + "PositionData.json", newposition);
        //Debug.Log(shiposition.text);
    }

Upvotes: 0

Views: 765

Answers (1)

derHugo
derHugo

Reputation: 90779

The JSON export itself should work that way

However, never use + "/" for system file paths. Rather use Path.Combine which inserts the correct path separator automatically

System.IO.File.WriteAllText(Path.Combine(Application.persistentDataPath, "DataCenter.json", data);

Main Problem

You are never assigning any values into the JSON_ShipData so you will always export a JSON with default values!

So first what you want is to store a Vector2Int for the position

[Serializable]
public class ShipData
{
    public Vector2Int position;
    public float depth;
    public float windspeed;
    public float temperature;
}

Then you probably would want to update the content at certain places like e.g.

private bool TryGetPosition(int[,] grid, out Vector2Int position)
{
    position = default;

    for (int x = 0; x < grid.GetLength(0); i++)
    {
        for (int y = 0; y < grid.GetLength(1); j++)
        {
            if (grid[x, y] == 1)
            {
                // store into the returned out value
                position = new Vector2Int(x, y);

                shiposition.text = $"X : {x} Y : {y}";
                shiposition.text.ToString();
                PlayerPrefs.SetInt("positionX", position.x);
                PlayerPrefs.SetInt("positionY", position.y);
                PlayerPrefs.Save();
                Debug.Log(shiposition.text);

                return true;
            }
        }
    }

    return false;
}

Note that this is also more efficient since it doesn't iterate through the rest of your grid if it already has found the position

Repeat the same for your other methods and then use them like e.g.

public void button()
{
    // Check if a position is found and if yes update the json data
    if(TryGetPosition(grid, out var position)
    {
        JSON_ShipData.position = position;
    }

    // Repeat the same for your other values

    SaveintoJson();
}

General notes:

Before doing stuff like

grid[p1, --p2] = 1;

You should always check if your are maybe getting out of bounds e.g. like

private bool TryGoToPosition(int[,] grid, Vector2Int from, Vector2Int to)
{
    if(to.x >= 0 && to.x < grid.GetLength(0) - 1 && to.y >= 0 && to.y < grid.GetLength(1) - 1)
    {
        grid[from.x, from.y] = 0;
        grid[to.x, to.x] = 1;
    }
    else
    {
        Debug.LogWarning("Reached grid border! -> Ignored");
    }
}

Then I would simply work with a Vector2Int in general instead of setting some value in a grid to 0 or 1 like

Vector2Int gridDimensions = new Vector2Int(10, 16);
public ShipData currentShipData;
public ShipData JSON_ShipData;

private bool CanGoToPosition(Vector2Int to)
{
    return to.x >= 0 && to.x < gridDimensions.x - 1 && to.y >= 0 && to.y < gridDimensions.y - 1;
}

void Start()
{
    currentShipData.position = new Vector2Int(9, 0);

    panelhole.SetActive(false);
    panelturtle.SetActive(false);
    Debug.Log(JSON_ShipData.position);
    Debug.Log(shiposition.transform.position);
}

void Update()
{
    ......        

    if (Input.GetKeyDown(KeyCode.A))
    {
        if (CanGoToPosition(JSON_ShipData.position + Vector2Int.down))
        {
            currentShipData.position += Vector2Int.down;
        }
        else
        {
            Debug.Log("You can't move left!!");
        }
    }

    ...

    // Then after you handled user input for movement update the other data
    currentShipData.windspeed = windspeedData[JSON_ShipData.position.x, JSON_ShipData.position.y];
    currentShipData.flow = flowData[JSON_ShipData.position.x, JSON_ShipData.position.y];
    ...
}

Then for the button press you simply only copy over the current values

public void button()
{
    JSON_ShipData.position = currentShipData.position;
    ...

    SaveintoJson();
}

Upvotes: 1

Related Questions