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)
[180371-sceneview.jpg*|180371]
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*;*
*Vector3 pos = lvlObj.transform.position;*
*string posOutput = JsonUtility.ToJson(pos);*
*File.WriteAllText(path,posOutput);*
*Debug.Log("position:" + posOutput);*
*}*
*}*
*}*
*```*
*