- Home /
how to write GameObject position in the Scene to json file ?
on Clicking the button, I m loading the function WriteJsonForLevel(). I have placed three GameObject with the tag name "RedCoin" and I want to write the position of the GameObject to a JSON file. I can get the position of the object, but it's all overwritten.I can only see the last GameObject position (i.e the completion of the loop) ``` using System.Collections; using System.Collections.Generic; using UnityEngine; using System.IO;
public class Writedatajsonfile : MonoBehaviour {
public List<GameObject> levelObjects;
public string level;
public Vector3 pos;
// Start is called before the first frame update
void Start()
{
levelObjects = new List<GameObject>();
}
// Update is called once per frame
void Update()
{
}
public void WritejsonForAll()
{
WriteJsonForLevel();
}
public void WriteJsonForLevel()
{
/* FileStream fs = new FileStream(Application.dataPath + "/sample.json",FileMode.Create);
StreamWriter writer= new StreamWriter(fs);*/
GameObject[] coinObjRed = GameObject.FindGameObjectsWithTag("RedCoin");
putAllObjectInList(coinObjRed);
}
public void putAllObjectInList(GameObject[] p)
{
string path = Application.dataPath + "/text.json";
foreach (GameObject q in p)
{
levelObjects.Add(q);
}
for (int i = 0; i < levelObjects.Count; i++)
{
GameObject lvlObj = levelObjects[i];
Vector3 pos = lvlObj.transform.position;
string posOutput = JsonUtility.ToJson(pos);
File.WriteAllText(path,posOutput);
Debug.Log("position:" + posOutput);
}
}
}
```
Answer by HellsHand · May 07, 2021 at 02:18 PM
The issue your running into is that File.WriteAllText()
opens the file, writes to it and then closes the file. Every iteration of your loop overwrites the previous iteration. You will need to put all the pos
into a single List or Array and pass that as json to File.WriteAllText()
after the loop completes. This is a simplified example:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
public class Writedatajsonfile : MonoBehaviour
{
public void WriteJsonForLevel()
{
GameObject[] levelObjects = GameObject.FindGameObjectsWithTag("RedCoin");
string path = Application.dataPath + "/text.json";
ListSerializer pos = new ListSerializer();
for (int i = 0; i < levelObjects.Length; i++)
{
pos.posList.Add(levelObjects[i].transform.position);
}
string posOutput = JsonUtility.ToJson(pos);
File.WriteAllText(path, posOutput);
Debug.Log("position:" + posOutput);
}
}
[Serializable]
public class ListSerializer
{
public List<Vector3> posList = new List<Vector3>();
}
Thank you. I'm happy. But when I add another object say FindGameObjectwithTag('GreenCoin") the second content is replaced.Can you have solution for that.I have to add all objects.As I'm a newbie I find very difficult to implement Serialize data.
``` using System.Collections; using System.Collections.Generic; using UnityEngine; using System.IO;
public class Unityhelp : MonoBehaviour { public List levelObjects; // Start is called before the first frame update void Start() { levelObjects = new List(); }
// Update is called once per frame
void Update()
{
}
public void WritejsonForAll()
{
WriteJsonForLevel();
}
public void WriteJsonForLevel()
{
GameObject[] coinObjRed = GameObject.FindGameObjectsWithTag("RedCoin");
putAllObjectInList(coinObjRed);
GameObject[] coinObjGreen = GameObject.FindGameObjectsWithTag("GreenCoin");
putAllObjectInList(coinObjGreen);
}
public void putAllObjectInList(GameObject[] p)
{
string path = Application.dataPath + "/sample.json";
ListSerializer pos = new ListSerializer();
foreach (GameObject obj in p)
{
pos.posList.Add(obj.transform.position);
}
string posOutput = JsonUtility.ToJson(pos);
File.WriteAllText(path, posOutput);
Debug.Log("position:" + posOutput);
}
}
[System.Serializable] public class ListSerializer { public List posList = new List(); }
```
using System;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
public class Writedatajsonfile : MonoBehaviour
{
public void WriteJsonForLevel()
{
string path = Application.dataPath + "/text.json";
ListSerializer pos = new ListSerializer();
GameObject[] levelObjects = GameObject.FindGameObjectsWithTag("RedCoin");
for (int i = 0; i < levelObjects.Length; i++)
{
pos.redPosList.Add(levelObjects[i].transform.position);
}
levelObjects = GameObject.FindGameObjectsWithTag("GreenCoin"); //Reinitialize levelObjects
for (int i = 0; i < levelObjects.Length; i++) //Loop through and add to appropriate list
{
pos.greenPosList.Add(levelObjects[i].transform.position);
}
string posOutput = JsonUtility.ToJson(pos);
File.WriteAllText(path, posOutput);
Debug.Log("position:" + posOutput);
}
}
[Serializable]
public class ListSerializer
{
public List<Vector3> redPosList = new List<Vector3>();
public List<Vector3> greenPosList = new List<Vector3>(); //New list for each object set
}
This would add another coin. All you need to do for any further additions is add a new List to ListSerializer
and reinitialize levelObjects
with the new array and loop through the same as the first objects adding them to their own list.
When you want to load back in you could use something like:
public static ListSerializer LoadData()
{
string path = Application.dataPath + "/text.json";
if (File.Exists(path ))
{
string jsonString = File.ReadAllText(path );
Debug.Log("Game Loaded");
return JsonUtility.FromJson<ListSerializer>(jsonString);
}
}
Then you would call it as:
ListSerializer loadedList = LoadData();
and access it's properties to get back the Vectors with:
loadedList.greenPosList[index];