IT_Games/Unity3D

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

JJun ™ 2013. 6. 20. 15:15

 


출처: http://blueasa.tistory.com/937


 


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

pc에선 잘되지만 모바일에서만 이상이있었음. 찾다 찾다 유니티 포럼에서 좋은거 긁어왔습니다. ㅋㅋ

아이폰도 됩니다~

 

 

public void writeStringToFile( string str, string filename )
{
   #if !WEB_BUILD

       string path = pathForDocumentsFile( filename );
       FileStream file = new
FileStream (path, FileMode.Create, FileAccess.Write);
  

       StreamWriter sw = new StreamWriter( file );
  
     sw.WriteLine( str );
  

       sw.Close();
 
      file.Close();
   #endif

}


public string readStringFromFile( string filename)//, int lineIndex )

{
   #if !WEB_BUILD

       string path = pathForDocumentsFile( filename );
 

       if (File.Exists(path))
       {
          FileStream file = new
FileStream (path, FileMode.Open, FileAccess.Read);
          StreamReader sr = new
StreamReader( file );
 

          string str = null;
          str =
sr.ReadLine ();
 

          sr.Close();
          file.Close();
 

          return str;
       }
       else

       {
          return null
;
       }

  #else
       return null;

  #endif 

}

// 핵심!
public string pathForDocumentsFile( string
filename )

     if (Application.platform ==
RuntimePlatform.IPhonePlayer)
 
    {
         string path = Application.dataPath.Substring( 0, Application.dataPath.Length - 5
);
         path = path.Substring( 0, path.LastIndexOf( '/'
) );
         return Path.Combine( Path.Combine( path, "Documents"
), filename );
 
    }
     else if(Application.platform ==
RuntimePlatform.Android)
 
    {
         string path =
Application.persistentDataPath; 
         path = path.Substring(0, path.LastIndexOf( '/'
) ); 
         return
Path.Combine (path, filename);
 
    } 
     else
 
 
    {
         string path =
Application.dataPath; 
         path = path.Substring(0, path.LastIndexOf( '/'
) );
         return
Path.Combine (path, filename);
 
    }
}