Django Girls and Boys 備忘録

Python、Selenium、Django、java、iPhoneアプリ、Excelマクロなどで気付いたこと、覚えておきたいことなどを載せていきます。

【Unity】文字列データなどをテキストファイルとして書き込む方法

 

 

 

Unity側で扱っていた変数などの文字列データをテキストファイルに出力する場合の方法についての説明になります。

 

目次

 

 

1.書き込み用コード概要説明

 

コードの先頭でusing System.IOを宣言しておく必要があります。

 

using System.IO;

 

また、あらかじめAssetsフォルダ内に「textData.txt」を用意しておきます。

その上で、たとえば以下のように書き込み用の文字列を用意します。

 

//変数string を書き込み
private string string = "1234567";

 

その後は、StreamWriterを使用し以下のようにすることで文字列をバッファに取り込んでから用意したテキストファイルへ書き出します。

その後Flushにて書き残しチェックを行いCloseでファイルをクローズします。

StreamWriterの第二引数をTrueにすると上書き保存されます。

 

StreamWriter sw = new StreamWriter( "textData.txt", false);
sw.WriteLine(stepCntString);
sw.Flush();
sw.Close();

 

 

2.テキストファイル書き込み例

 

 

それらを通したおよそのコード例としては以下のようになります。

以下の例では、Start内でファイルがない時の作成処理を追加しています。

 

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

// RaycastAgent
public class Output : MonoBehaviour
{
:
:
private string  fileName;
private string  filepath;
private string  stepCntString;

// Start is called before the first frame update
void Start()
{

// パス名取得
fileName = "stepCount.txt";
filepath = Application.dataPath + "/" + fileName;
stepCntString = "";

// ファイルがないとき、ファイル作成
if (!File.Exists(filepath)) {
  StreamWriter sw = new StreamWriter(filepath, true);    // ファイル書き込み指定
  sw.WriteLine(stepCntString);                           // 情報を書き込み
  sw.Close();
}
:
:
:
//変数stepCntString を書き込み
stepCntString = "1234567";

StreamWriter sw = new StreamWriter( filepath, false);
sw.WriteLine(stepCntString);
sw.Flush();
sw.Close();
:
:
}

 

以上がUnityで文字列データなどをテキストファイルとして書き込む方法の例と簡単な説明になります。