Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by Kathiravan · May 06, 2021 at 06:22 PM · json

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) alt text ``` 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);
 
     }
 }

}

```

sceneview.jpg (22.8 kB)
Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
1

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>();
 }

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Kathiravan · May 07, 2021 at 05:23 PM 0
Share

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(); }

```

alt text

sceneview2.jpg (21.8 kB)
avatar image HellsHand Kathiravan · May 07, 2021 at 05:38 PM 0
Share
 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];

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

119 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Best Way to Store Large Number of GameObjects? 1 Answer

Loading JSON into JSON issue,JSON file inside JSON problem 0 Answers

How to Parse the JSON to get an array of image URLs. 0 Answers

i am fetch the images using (j son)server but it take too much time?? 0 Answers

Save Game format that is change proof and secure 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges