Unity3D

text 파일 Read/Write 하는 소스 몇가지

blueasa 2012. 10. 22. 01:10

유니티3D에서 text 파일 읽고/쓰는 소스코드 몇가지를 올립니다. 
이거 잘 안되서 저는 엄청 혼났거든요. 
아래 소스들 중 골라서 사용해보세요. 

1. c#코드, FileInfo 클래스 사용하는게 특징이네요. 
파일 읽기는 부분만 있습니다. 

using System; 
using System.IO; 

public class LineReader : MonoBehaviour 

    protected FileInfo theSourceFile = null; 
    protected StreamReader reader = null; 
    protected string text = " "; // assigned to allow first line to be read below 

    void Start () { 
        theSourceFile = new FileInfo ("Test.txt"); 
        reader = theSourceFile.OpenText(); 
    } 
    
    void Update () { 
        if (text != null) { 
            text = reader.ReadLine(); 
            //Console.WriteLine(text); 
            print (text); 
        } 
    } 


******* 
2. javascript 코드, 
파일 읽고/쓰는 함수가 다 있습니다. 
읽을 때 File 클래스를 사용합니다. 

import System.IO; 
var filePath = "/Users/ResetOfDirectoryPath/testWrite.txt"; 

function Update() { 
if (Input.GetKeyDown("r")) { 
WriteFile(filePath); 

if (Input.GetKeyDown("f")) { 
ReadFile(filePath); 



function WriteFile(filepathIncludingFileName : String) 

var sw : StreamWriter = new StreamWriter(filepathIncludingFileName); 
sw.WriteLine("Line to write"); 
sw.WriteLine("Another Line"); 
sw.Flush(); 
sw.Close(); 


function ReadFile(filepathIncludingFileName : String) { 
sr = new File.OpenText(filepathIncludingFileName); 

input = ""; 
while (true) { 
input = sr.ReadLine(); 
if (input == null) { break; } 
Debug.Log("line="+input); 

sr.Close(); 


****** 
3. javascript 코드, 파일 읽기는 부분만인데 
읽을 때 StreamReader 클래스를 이용합니다. 

import System.IO; 
var fileName = "foo.txt"; 
function Start () 

    var sr = new StreamReader(Application.dataPath + "/" + fileName); 
    var fileContents = sr.ReadToEnd(); 
    sr.Close(); 
    var lines = fileContents.Split("\n"[0]); 
    for (line in lines) { 
        print (line); 
    } 


***** 
4. 기타 
이 부분은 저도 테스트를 못했습니다. 
var pathToFile = "path/to/example.txt"; 
var url = "file://" + pathToFile; 
yiel download = new WWW(url); 
text = download.data; 

**** 
여기 나온 코드들은 unity3d 포럼에 나와있는 코드들인데 개발 시에 사용하려고 복사해뒀던 것들입니다.



출처 : http://www.applclub.com/bbs/board.php?bo_table=F&wr_id=1170&sca=%B0%AD%C1%C2%2F%C6%C1

반응형