在 Unity 中将游戏内数据导出到 csv

Exporting in-game data to csv in Unity

我想将我的计数器数据和时间导出为 csv 文件,然后我将用它们制作一个二维图。如何将这些记录并写入 csv 文件?

你的问题很宽泛,不过今天我正好有心情^^

据我了解,您实际上是在问以下问题:

How do I store counter values with a time value?

我会使用合适的类型 List 例如

[Serializable]
public class KeyFrame
{
    public int Value;
    public float Time;

    public KeyFrame(){}

    public KeyFrame (int value, float time)
    {
        Value = value;
        Time = time;
    }
}

private List<KeyFrame> keyFrames = new List<KeyFrame>(10000);

然后我会让我的计数器成为 Property 每次更改值时它都会跟踪列表中的新条目

private int _counter;
public int Counter
{
    get => _counter;
    set
    {
        _counter = value;
        keyFrames.Add(new KeyFrame (value, Time.time));
    }
}

现在每次你做,例如

Counter++;

与当前 Time.time

的新条目

The time in seconds since the app was started.

已添加到列表中,因此您应该另外使用 0

对其进行初始化
private void Start ()
{
    Counter = 0;
}

How to a create a CSV content from a given set of 2D coordinates?

public string ToCSV()
{
    var sb = new StringBuilder("Time,Value");
    foreach(var frame in keyFrames)
    {
        sb.Append('\n').Append(frame.Time.ToString()).Append(',').Append(frame.Value.ToString());
    }

    return sb.ToString();
}

这会创建一个字符串,例如

Time,Value
0,0
2.288847,1
4.2887477,2
...

How do I write to a file?

通常你应该写入Application.persistentDataPath or in the Editor also the Application.streamingAssetsPath

你可以,例如使用 StreamWriter 或者简单地使用 File.WriteAllText

#if UNITY_EDITOR
using UnityEditor;
#endif

...

public void SaveToFile ()
{
    // Use the CSV generation from before
    var content = ToCSV();

    // The target file path e.g.
#if UNITY_EDITOR
    var folder = Application.streamingAssetsPath;

    if(! Directory.Exists(folder) Directory.CreateDirectory(folder);
#else
    var folder = Application.persistentDataPath;
#endif

    var filePath = Path.Combine(folder, "export.csv");

    using(var writer = new StreamWriter(filePath, false))
    {
        writer.Write(content);
    }

    // Or just
    //File.WriteAllText(content);

    Debug.Log($"CSV file written to \"{filePath}\"");

#if UNITY_EDITOR
    AssetDatabase.Refresh();
#endif
}