Search code examples
c#csvunity-game-enginecsvreader

CSVReader "Script serialization error" for Unity


I have some really big problem. I try to read my csv files using CSVReader, but I have an error, "Script serailzation" What should I do? Please help me! Here is my code. I'm trying to check my path and folders name, but I can't fix it.

Error screenshot

//CSVReader Script

using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;

public class CSVReader
{
    static string SPLIT_RE = @",(?=(?:[^""]*""[^""]*"")*(?![^""]*""))";
    static string LINE_SPLIT_RE = @"\r\n|\n\r|\n|\r";
    static char[] TRIM_CHARS = { '\"' };

    public static List<Dictionary<string, object>> Read(string file)
    {
        var list = new List<Dictionary<string, object>>();
        TextAsset data = Resources.Load(file) as TextAsset;

        var lines = Regex.Split(data.text, LINE_SPLIT_RE);

        if (lines.Length <= 1) return list;

        var header = Regex.Split(lines[0], SPLIT_RE);
        for (var i = 1; i < lines.Length; i++)
        {

            var values = Regex.Split(lines[i], SPLIT_RE);
            if (values.Length == 0 || values[0] == "") continue;

            var entry = new Dictionary<string, object>();
            for (var j = 0; j < header.Length && j < values.Length; j++)
            {
                string value = values[j];
                value = value.TrimStart(TRIM_CHARS).TrimEnd(TRIM_CHARS).Replace("\\", "");
                object finalvalue = value;
                int n;
                float f;
                if (int.TryParse(value, out n))
                {
                    finalvalue = n;
                }
                else if (float.TryParse(value, out f))
                {
                    finalvalue = f;
                }
                entry[header[j]] = finalvalue;
            }
            list.Add(entry);
        }
        return list;
    }
}

Code screenshot 1 (CSV Reader class)

Code screenshot 2 (language : MonoBehaviour class


Solution

  • You have a clear description of the problem in the console as I see on the first image.

    You are trying to make the problematic call on assigning your data_lang variable in the language script. Change it with something like

    class language : MonoBehavuiour
    {
        List<Dictionary<string, object>> data_lang;
    
        void Awake()
        {
            data_lang = CSVReader.Read("lang");
            
            // do your other staff here
        }
    }
    

    how it is advised in the error message and it should work fine