Skip to content

Instantly share code, notes, and snippets.

@makochang
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save makochang/71d18270d344b9873b6c to your computer and use it in GitHub Desktop.
Save makochang/71d18270d344b9873b6c to your computer and use it in GitHub Desktop.
Unity C#でファイルの読み書きをする
using UnityEngine;
using System.Collections;
using System.IO;
public class FileIO : MonoBehaviour
{
//ファイル名.
private string fileName = "theFile.txt";
//データパス.
private string dataPath;
/// <summary>
/// ファイルを読み込む.ファイルが存在しない場合は作成する.
/// </summary>
private void FileRead ()
{
FileStream fs;
Debug.Log (dataPath + "を読み込みます.");
try {
fs = new FileStream (dataPath, FileMode.Open, FileAccess.Read);
} catch (IOException) {
Debug.Log (dataPath + "が読み込めませんでした.");
FileWrite ("");
return;
}
StreamReader sr = new StreamReader (fs);
string readData = sr.ReadLine ();
Debug.Log (readData);
sr.Close ();
fs.Close ();
}
/// <summary>
/// ファイルを書き込む.
/// </summary>
/// <param name="writeData">書き込むデータ.</param>
private void FileWrite (string writeData)
{
Debug.Log (dataPath + "に" + writeData + "を書き込みます.");
FileStream fs;
try {
fs = new FileStream (dataPath, FileMode.Create, FileAccess.Write);
} catch (IOException) {
Debug.Log (dataPath + "に書き込めませんでした.");
return;
}
StreamWriter sw = new StreamWriter (fs);
sw.Write (writeData);
sw.Flush ();
sw.Close ();
fs.Close ();
}
/// <summary>
/// ファイルを初期化する.
/// </summary>
public void InitSaveData ()
{
FileWrite ("");
Debug.Log ("セーブデータを初期化しました.");
}
/// <summary>
/// 起動時にファイルを読み込む.
/// </summary>
private void Awake ()
{
dataPath = Application.persistentDataPath + fileName;
FileRead ();
}
/// <summary>
/// 動作確認用.Fire1でプレイ時間を保存、Jumpでロードしコンソールに表示.
/// </summary>
private void Update ()
{
if (Input.GetButtonDown ("Fire1")) {
FileWrite (Time.time.ToString ());
}
if (Input.GetButtonDown ("Jump")) {
FileRead ();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment