0

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);
    }
3
  • 1
    If you have an object you can just call JsonConvert.SerializeObject() to convert to a JSON string. Have a look at the JSON.NET docs here: newtonsoft.com/json/help/html/… - you can get back to an object by using JsonConvert.DeserializeObject() - this will take a JSON string and read it into a target object. Commented Jul 1, 2020 at 9:55
  • if @Charleh solution doesn't work. Find out how to use Newtonsoft in Unity for serializing complex objects. Commented Jul 1, 2020 at 10:07
  • It should work this way ... however I don't see at which place you ever update the values in JSON_ShipData .... Commented Jul 1, 2020 at 10:18

1 Answer 1

1

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();
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you for your suggestion, it's works well. I have another question. How do I keep the previous information (position, depthsea, windspeed, temperature) on the world space. Because I want users to investigate while observing the previous values.
What do you mean? Maybe after the button press set a bool flag and skip the according part(s) in Update or something?
I mean (for example, when the button is pressed the ship position appears (x : 9, y : 0) .. Then when I move the ship to position (x : 9,y : 3) ... the value (x: 9, y: 0) still appears on worldspace). So there will be 2 value in screen which is (x : 9, y : 0 and x : 9,y : 3). How to keep that value on screen?
Just store it in a second instance of ShipData .. lets say one is the field public ShipData currentData; here you move on etc. On Button press store the value in a second one like the public ShipData JSON_ShipData; (you can simply copy over the values from the currentData) -> This way you have both "snapshots" at the same time and could implement your display to show both values
Dear Hugo ~ I had a problem when I wanted to crash(collision) the ship to the rock. I can return the position of the ship to the previous position, but not in the order of the array (which contains information inside). Do you have a recommendation?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.