LoginSignup
8
7

More than 5 years have passed since last update.

Unity csv読込

Posted at

メモ

現時点ではメモとして記録。あとでまとめる。

Unityでcsvを読み込む際に必要なライブラリは

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

の4つ。

今回はcsvのデータが

0.00203,0.00203,0.00203,
0.02492,0.02492,0.02492,
-0.08662,-0.08662,-0.08662,
-0.11209,-0.11209,-0.11209,
-0.15269,-0.15269,-0.15269,
0.18988,0.18988,0.18988,
0.59541,0.59541,0.59541,
0.79057,0.79057,0.79057,
0.87872,0.87872,0.87872,
0.43291,0.43291,0.43291,
0.25082,0.25082,0.25082,
0.26784,0.26784,0.26784,
0.22023,0.22023,0.22023,
0.33144,0.33144,0.33144,

といったデータ。(iPhoneの加速度センサを利用して取得したX,Y,Z順のデータ)

ソース全体としてはこんな感じ。

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
public class move : MonoBehaviour {

    string[] ad;
    string[] ad_x;
    string[] ad_y;
    string[] ad_z;

    int numberOfLines = 0;

    // Use this for initialization
    void Start () {

        TextAsset adTextFile = Resources.Load("text/AD", typeof(TextAsset)) as TextAsset;
        ad = adTextFile.text.Split("\n"[0]);

        ad_x = new string[ad.Length];
        ad_y = new string[ad.Length];
        ad_z = new string[ad.Length];

        for (int i = 0; i < ad.Length; i ++)
        {
            ad_x[i] = ad[i].Split(","[0])[0];
            ad_y[i] = ad[i].Split(","[0])[1];
            ad_z[i] = ad[i].Split(","[0])[2];
            numberOfLines++;
        }

        Debug.Log(numberOfLines);

        for (int i = 0; i< 2; i ++)
        {
            Debug.Log(ad_x[i]);
            Debug.Log(ad_y[i]);
            Debug.Log(ad_z[i]);
        }
    }

    // Update is called once per frame
    void Update () {

    }
}

Assetsフォルダ下に「Resources」フォルダを作成し、「Resources」フォルダの階層にさらに「text」フォルダを作成。

ここでポイントメモ。

ad[i].Split(","[0])[0];
ad[i].Split(","[0])[1];
ad[i].Split(","[0])[2];

と書くと、i行目の各成分を取得できる。

ad[i].Split(","[0]);

と書くと、i行目のすべての成分を取得できる。
なので、レコードとして取得したいときは

ad[i].Split(","[0]);

と書くといい。

8
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
7