Export CSV from Unity

How to export CSV from Unity with a C# script: what changes when data becomes delimited text, where files are written, and how to keep the output readable in spreadsheets.

Unity has no general-purpose "Export to CSV" command for game data. To get scores, telemetry, level data or ScriptableObject contents into a spreadsheet, you usually write a small C# script that converts your data into comma-separated text and saves it to a file. This review covers what that conversion changes, where it holds up, and where it can quietly corrupt or mislead.

Is CSV export suitable for your use?

CSV fits flat, row-and-column data you want to open in a spreadsheet, diff in version control, or pass to analysis tools: one record per row, one value per column. Its main benefit is that almost every spreadsheet and data tool can read it.

The main tradeoff is structure. CSV has no types, nesting or schema. Nested objects, lists inside a record, references between assets, and the difference between a number and the text "007" are not preserved unless you flatten and document them yourself. If you need to load the data back into Unity with its structure intact, JSON (for example through JsonUtility) or Unity's own serialized assets are usually the better choice, with CSV as a secondary export for people working in spreadsheets.

Plain unstructured text, such as a log file, is preferable when the output is meant for reading line by line rather than sorting or filtering by column. TSV (tab-separated values) is worth considering when your fields often contain commas, such as free-text descriptions, because tabs rarely appear in that kind of content.

What the export actually changes

Exporting to CSV is serialization, not a visual effect. Values held in memory as C# types (int, float, bool, Vector3, enums, strings) are converted to characters and joined with delimiters. The stored file contains only text. Anything that is not written out explicitly, such as a field's type, units or the object it belonged to, is gone from the file.

Several conversions need deliberate handling:

  • Numbers: float.ToString() follows the current culture by default, so on a machine set to a locale that uses decimal commas, 1.5 can become "1,5" and break the column layout. Format numbers with CultureInfo.InvariantCulture.
  • Compound types: a Vector3 needs to be split into separate x, y and z columns, or written as one quoted field. Splitting is usually easier to work with in a spreadsheet.
  • Text fields: values containing a comma, a double quote or a line break must be wrapped in double quotes, and any double quote inside the value must be doubled. This is the common convention described in RFC 4180 and expected by most CSV readers.
  • Encoding: the characters in the file depend on the encoding you choose. UTF-8 is the usual choice, and it matters when names or descriptions include non-ASCII characters.

The script below is a minimal example of those rules. It escapes fields, uses invariant formatting for numbers, and writes UTF-8 with a byte order mark. It is illustrative and has not been tested against a specific Unity version here, so treat it as a starting point and check it against your own data.

using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using UnityEngine;

public static class CsvExporter
{
    static readonly char[] SpecialChars = { ',', '"', '\n', '\r' };

    public static string Escape(string field)
    {
        if (string.IsNullOrEmpty(field)) return "";
        string escaped = field.Replace("\"", "\"\"");
        return field.IndexOfAny(SpecialChars) >= 0 ? "\"" + escaped + "\"" : escaped;
    }

    public static string Write(string fileName, IEnumerable<string[]> rows)
    {
        var sb = new StringBuilder();
        foreach (var row in rows)
        {
            for (int i = 0; i < row.Length; i++)
            {
                if (i > 0) sb.Append(',');
                sb.Append(Escape(row[i]));
            }
            sb.Append("\r\n");
        }

        string path = Path.Combine(Application.persistentDataPath, fileName);
        File.WriteAllText(path, sb.ToString(), new UTF8Encoding(true));
        return path;
    }
}

// Example usage
// var inv = CultureInfo.InvariantCulture;
// var rows = new List<string[]> { new[] { "name", "score", "pos_x", "pos_y", "pos_z" } };
// rows.Add(new[] { player.name, score.ToString(inv),
//     pos.x.ToString("R", inv), pos.y.ToString("R", inv), pos.z.ToString("R", inv) });
// Debug.Log("CSV written to " + CsvExporter.Write("scores.csv", rows));

Where the file ends up

Application.persistentDataPath is the usual writable location in builds, and its actual folder differs by platform. Application.dataPath points inside the project in the Editor, but it should not be relied on for writing in player builds. For exports that only designers or developers need, an Editor script with a MenuItem attribute that writes into the project folder keeps export code out of the shipped game.

WebGL builds run in a browser sandbox and cannot write freely to the user's file system, so a standard file write will not produce a downloadable file there. Getting a CSV out of a WebGL build generally requires a browser-side download mechanism. Platform-specific behavior on consoles and mobile devices was not verified for this article; check Unity's documentation for your target platform.

Will the file stay readable after sharing?

CSV is plain text, so copying it, emailing it or committing it to version control does not change its contents. Problems tend to appear when it is opened, because each application interprets the text in its own way.

Issue | What can happen | Mitigation
Delimiter and locale | Some spreadsheet setups expect semicolons instead of commas, so all values land in one column | Use the program's import dialog to set the delimiter, or export TSV
Encoding | Accented or non-Latin characters can display incorrectly if the file is not read as UTF-8 | Write UTF-8; adding a byte order mark helps some spreadsheet programs detect it
Automatic type conversion | Spreadsheets may drop leading zeros, turn IDs into scientific notation, or read values as dates | Import the affected columns as text instead of opening the file directly
Formula injection | Fields starting with =, +, - or @ may be treated as formulas when opened | For untrusted text such as player names, prefix risky values; note this changes the stored data
Line breaks in fields | Readers that ignore quoting split one record into several rows | Quote such fields, or strip line breaks if they are not needed

Behavior varies by spreadsheet program, version and locale settings. No destination was tested for this article, so confirm with a sample file in the specific tool your team uses rather than assuming one successful import applies everywhere.

On accessibility: a CSV file has no headings, captions or reading-order markup of its own. Screen readers read it as a grid once a spreadsheet opens it, or as a run of comma-separated text in a plain editor. Clear header names in the first row help in both cases. If the data is meant for a report rather than further analysis, a formatted document or a table with a descriptive summary is easier to follow.

Gaps in this review

No benchmarks, version-specific test results or third-party Unity packages were assessed. Asset Store or package-based CSV tools may add features such as reflection-based column mapping, but their behavior and data handling were not reviewed here and should be checked against their own documentation.