LoginSignup
92
83

More than 5 years have passed since last update.

Unityで外部データ読み込み

Last updated at Posted at 2014-09-16

外部ファイルの読み込み

キーを押したらファイル読み込みするサンプル
印象としては、Windowsでのファイル読み込みの作りと同じですね

用途的には外部ファイルをデータとして使えると
ゲームで、スクリプトをいじらず
外部ファイルで調整が出来る点ですね

FileOpen.cs

using UnityEngine;
using System.Collections;
using System.IO; //System.IO.FileInfo, System.IO.StreamReader, System.IO.StreamWriter
using System; //Exception
using System.Text; //Encoding

// ファイル読み込み
public class FileOpen : MonoBehaviour {

    private string guitxt = "";

    // Update is called once per frame
    void Update () {
        // スペースキーを押したらファイル読み込みする
        if (Input.GetKeyDown (KeyCode.Space)) {
            ReadFile ();
        }   
    }
    // 読み込んだ情報をGUIとして表示
    void OnGUI()
    {
        GUI.TextArea (new Rect (5, 5, Screen.width, 50), guitxt);
    }

    // 読み込み関数
    void ReadFile(){
        // FileReadTest.txtファイルを読み込む
        FileInfo fi = new FileInfo(Application.dataPath + "/" + "FileReadTest.txt");
        try {
            // 一行毎読み込み
            using (StreamReader sr = new StreamReader(fi.OpenRead(), Encoding.UTF8)){
                guitxt = sr.ReadToEnd();
            }
        } catch (Exception e){
            // 改行コード
            guitxt += SetDefaultText();
        }
    }

    // 改行コード処理
    string SetDefaultText(){
        return "C#あ\n";
    }
}

外部ファイルのファイル位置

FileOpen.png

実行ファイルの直下を読み込む

結果

FileReadTest.png

参考サイト

おすすめ本
http://amzn.to/2nkXhSX

92
83
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
92
83