Home>

I want to output Cube X-coordinate values ​​on a randomly shaking floor to a CSV file.

Error message
I'm having trouble exporting CSV files.
Applicable source code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Text;
using System.IO;

public class TransformLogger: MonoBehaviour
{
    // List declaration
    private List<string>Xdisplacement = new List<string>();
    // Use this for initialization
    void Start ()
    {}
    void FixedUpdate ()
    {
        // get transform
        Transform myTransform = this.transform;
        // Get x coordinate based on world coordinates
        Vector3 worldPos = myTransform.position;
        float x = worldPos.x;
        // convert to string
        string dispX = x.ToString ();
        // Add characters to the list
        Xdisplacement.Add (dispX);
   }
 // Save processing
    public void SaveCSV ()
    {
        StreamWriter sw = new StreamWriter (Application.dataPath + "X-Displacement.csv", false, Encoding.GetEncoding ("UTF-8"));
        // header output
        string [] s1 = {"X-displacement", "(unit: m)"};
        string s2 = string.Join (",", s1);
        sw.WriteLine (s2);
        // data output
        sw.WriteLine (Xdisplacement);
        // Close StreamWriter
        sw.Flush ();
        sw.Close ();
    }
}

I tried to store strings in variables and output them in CSV, but it didn't work.
It may be the reason for bringing the data output after FixUpdate, but it is too beginner to find any other way.

Supplemental information (FW/tool version etc.)

Unity 2019.1.9f1
Visual Studio 2017 C #

  • Answer # 1

    Because I use File, I think that the flow is a little different, but below

    public void SaveCSV
    {
        String str = "X-displacement, (unit: m),";
        foreach (var item in Xdisplacement)
        {
            str = str + item + ",";// Join (although there is no problem with Join)
        }
        When str.Remove (str.Length-1);// foeach is used, ``, '' remains at the end, so the last character is deleted
        File.WriteAllText (
            Environment.CurrentDirectory + "\\ X-Displacement.csv", str);//File.WriteAllText to write to the file.
    }

    How about this?