「Unityで外部ファイルの読み書き(C#)」 http://itouhiro.hatenablog.com/entry/20130826/unity のJavaScript版。

#pragma strict
private var pathtxt:String = '';
function Start () {
var t1:String = Application.dataPath;
var t2:String = Application.persistentDataPath;
pathtxt = 'dataPath:'+t1+"\npersistentDataPath:"+t2;
Debug.Log(pathtxt);
}
function Update () {
}
function OnGUI(){
GUI.TextArea(new Rect(5,5,Screen.width,50), pathtxt);
}
// Unity Editor:
// dataPath:C:/Users/star/Documents/20140605readfile/Assets
// persistentDataPath:C:/Users/star/AppData/LocalLow/DefaultCompany/20140605readfile
// Windows exe
// exe: C:\Users\star\Documents\20140605readfile\20140605readfile.exe
// dataPath:C:/Users/star/Documents/20140605readfile/20140605readfile_Data
// persistentDataPath:C:/Users/star/AppData/LocalLow/DefaultCompany/20140605readfile
//
// exe: R:\20140605\20140605readfile.exe
// dataPath:R:/20140605/20140605readfile_Data
// persistentDataPath:C:/Users/star/AppData/LocalLow/DefaultCompany/20140605readfileなるほど、exeファイルの位置を変更すると、dataPathは位置が変わるけど、persistentDataPathは変わらないな。

#pragma strict
import System.IO; //FileInfo, StreamWriter, StreamReader
private var outputFilename:String = 'a.txt';
function Start () {
var guitxt:String = '';
guitxt = readFile('');
writeFile(guitxt);
}
function Update () {
}
function writeFile(outputStr:String):void {
var fi:FileInfo = new FileInfo(Application.dataPath +'/'+ outputFilename);
// using (var sw:StreamWriter = fi.AppendText()){
// sr.WriteLine(guitxt);
// }
var sw:StreamWriter = fi.AppendText();
sw.WriteLine(outputStr);
sw.Close();
}
function readFile(inputStr:String):String {
var fi:FileInfo = new FileInfo(Application.dataPath +'/'+ outputFilename);
var sr:StreamReader = new StreamReader(fi.OpenRead());
while( ! sr.EndOfStream){
inputStr += sr.ReadLine();
}
inputStr += SetDefaultTxt();
sr.Close();
return inputStr;
}
function SetDefaultTxt():String{
return 'NotC#,ButJSあ\n';
}'a.txt'は最初に作っておく必要がある。
ファイル読み書きちゃんとできてる。
しかし本物のJavaScriptとはずいぶん変わってる。
- JavaScriptなら
"use strict"と書くところを#pragma strictだし - ファイル読み書きなんて.NetすぎてC#書くのと変わらない
- 静的型付けはActionScript3に似てるけど、配列の扱いとか違うし
うーん、やはりC#使う方が素直だよなー、Unityの場合。
というか、ファイル読み書きとかWWWアクセスとかする場合、
- 「.Net」でどうやるかネット検索で調べる
- C#のサンプルをネットで見かける
- C#のサンプルをJavaScriptに書き換えればJavaScriptで使える
の手順になるのだが、この書き換え工程するくらいなら最初からC#でいいのでは?と思う。
また、WindowsのC#で書かれたライブラリはUnityでもそのまま使えることが多いが、ブラウザ向けJavaScriptライブラリは配列の扱いのちがいがあるからUnityでは使えなさそうだ。

Unity4ゲームコーディング 本当にゲームが作れるスクリプトの書き方
- 作者: 浅野祐一,荒川巧也
- 出版社/メーカー: SBクリエイティブ
- 発売日: 2014/03/28
- メディア: 大型本
- この商品を含むブログ (3件) を見る