Search Unity

Question Export data from List<> to .json file

Discussion in 'Scripting' started by S4MA3L, Aug 3, 2020.

  1. S4MA3L

    S4MA3L

    Joined:
    Apr 17, 2020
    Posts:
    38
    I am working on a simple AR 3d scanner project, and as a beginning I am trying to reconstruct a 3d model from a list of recorded point cloud data. I am kind of new to unity scripting and don't actually know how I can convert this list of added point clouds to a .json file to be referenced to later.

    So I need the list of vector3 postitions of the point cloud to be saved to a .json file in a persistent storage Location. Can anyone tell me how I can do this? I already have a list of vector3 data.
    Any help is greatly appreciated.
     
  2. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,338
    Unity's got a built in JSON converter, but it's a bit finicky - it can't directly serialize lists or arrays, so you have to stick the list/array inside a serializable class or struct. Here's an example:

    Code (csharp):
    1.  
    2. using System;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5.  
    6. [Serializable]
    7. public struct VectorContainer {
    8.     public List<Vector3> vectors;
    9. }
    10.  
    11. public class TestScript : MonoBehaviour {
    12.  
    13.     private void Start() {
    14.         var vectorContainer = new VectorContainer();
    15.  
    16.         // This would be your vectors:
    17.         vectorContainer.vectors = new List<Vector3> {
    18.             Vector3.back,
    19.             Vector3.down,
    20.             Vector3.up
    21.         };
    22.         var str = JsonUtility.ToJson(vectorContainer, true);
    23.  
    24.         // You'd write them to file instead of just printing them
    25.         Debug.Log(str);
    26.     }
    27. }
     
  3. jamespaterson

    jamespaterson

    Joined:
    Jun 19, 2018
    Posts:
    401
  4. S4MA3L

    S4MA3L

    Joined:
    Apr 17, 2020
    Posts:
    38
    Can't thank you enough
     
  5. S4MA3L

    S4MA3L

    Joined:
    Apr 17, 2020
    Posts:
    38