본문 바로가기

Study/Unity3D

Unity3D 모바일 디바이스에서 파일생성 및 읽고 쓰기

작업하던 도중 모바일에선 경로가 파일경로가 바뀌고 읽어오지못하는 문제가 발생하였다.

pc에선 잘되지만 모바일에서만 이상이있었음

찾다 찾다 유니티 포럼에서 좋은거 긁어왔습니다. ㅋㅋ 아이폰도 됩니다~

 

 

1 public void writeStringToFile( string str, string filename ) 2 { 3 #if !WEB_BUILD 4 string path = pathForDocumentsFile( filename ); 5 FileStream file = new FileStream (path, FileMode.Create, FileAccess.Write); 6 7 StreamWriter sw = new StreamWriter( file ); 8 sw.WriteLine( str ); 9 10 sw.Close(); 11 file.Close(); 12 #endif 13 }


1 public string readStringFromFile( string filename)//, int lineIndex ) 2 { 3 #if !WEB_BUILD 4 string path = pathForDocumentsFile( filename ); 5 6 if (File.Exists(path)) 7 { 8 FileStream file = new FileStream (path, FileMode.Open, FileAccess.Read); 9 StreamReader sr = new StreamReader( file ); 10 11 string str = null; 12 str = sr.ReadLine (); 13 14 sr.Close(); 15 file.Close(); 16 17 return str; 18 } 19 else 20 { 21 return null; 22 } 23 #else 24 return null; 25 #endif 26 }

// 파일쓰고 읽는넘보다 이놈이 핵심이죠
1 public string pathForDocumentsFile( string filename ) 2 { 3 if (Application.platform == RuntimePlatform.IPhonePlayer) 4 { 5 string path = Application.dataPath.Substring( 0, Application.dataPath.Length - 5 ); 6 path = path.Substring( 0, path.LastIndexOf( '/' ) ); 7 return Path.Combine( Path.Combine( path, "Documents" ), filename ); 8 } 9 else if(Application.platform == RuntimePlatform.Android) 10 { 11 string path = Application.persistentDataPath; 12 path = path.Substring(0, path.LastIndexOf( '/' ) ); 13 return Path.Combine (path, filename); 14 } 15 else 16 { 17 string path = Application.dataPath; 18 path = path.Substring(0, path.LastIndexOf( '/' ) ); 19 return Path.Combine (path, filename); 20 } 21 }



[출처] Unity3D 모바일(안드로이드) 파일생성 및 읽고 쓰기|작성자 호랑낚시