Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Importing Data and assigning it to a variable

Discussion in 'Scripting' started by Teeg, Aug 26, 2015.

  1. Teeg

    Teeg

    Joined:
    Feb 8, 2015
    Posts:
    1
    Hello, I am trying to import a set of data from a text file that is approximately and assign one column of this data to a variable. Has anyone done anything like this?
     
  2. gorbit99

    gorbit99

    Joined:
    Jul 14, 2015
    Posts:
    1,350
    Look into fileIO a bit. It gives functions, like opening a file, reading one line/character, etc.
     
    MagicZelda likes this.
  3. MagicZelda

    MagicZelda

    Joined:
    May 1, 2013
    Posts:
    90
    check out System.IO.File.ReadAllLines(@"path\filename.ext") this will read the data in and then using String.Split to convert each line to a string[] array. Then the string[0] should be first column. There are a lot of examples if u search bing or google.

    Have fun
     
  4. gorbit99

    gorbit99

    Joined:
    Jul 14, 2015
    Posts:
    1,350
    You should also look at deceloper rules, there's one rule, that everytime, you want to post something, search it on google, if you still can't solve the problem, post.
     
    MagicZelda likes this.
  5. MagicZelda

    MagicZelda

    Joined:
    May 1, 2013
    Posts:
    90
    heres a sample using List<T>, not tested didnt have time sorry

    public List<string> FileToListOfString(string FileName,int colIndex)
    {

    List<String> values = new List<string>(); //creates a string list
    string[] strLines = File.ReadAllLines(FileName); //strLines holds each line of the file

    foreach (string strLine in strLines) //for each line in the loaded lines strLines get the column passed in via colIndex
    {
    //assuming its a comma seperated file else replace ',' with what ever char your data is split by ie ';' or '|' etc
    values.Add(strLine.Split(',')[colIndex].ToString());
    }

    return values;
    }
     
  6. gorbit99

    gorbit99

    Joined:
    Jul 14, 2015
    Posts:
    1,350
    MagicZelda, you should use code tags, they are under import/code on the comment toolbar.
     
  7. MagicZelda

    MagicZelda

    Joined:
    May 1, 2013
    Posts:
    90
    sorry was late and ive never put code up before lol. Will remember for next time