'2014/07/07'에 해당되는 글 2건

  1. 2014.07.07 [펌][ Unity3D ] 모바일(안드로이드) 파일생성 및 읽고 쓰기 Unity3D
  2. 2014.07.07 에셋번들 관련 글 및 링크 모음

[펌][ Unity3D ] 모바일(안드로이드) 파일생성 및 읽고 쓰기 Unity3D

|

2013/01/21 11:48

복사 http://blog.naver.com/nameisljk/110157303742

전용뷰어 보기

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

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);
}
}


Trackback 0 And Comment 0

에셋번들 관련 글 및 링크 모음

|

에셋번들 예제


http://u3d.as/1qS








에셋번들 관련 글



파일에 쓰는법


var cache = new System.IO.FileStream( 저장할 경로 , System.IO.FileMode.Create);
cache.Write(download.bytes, 0, download.bytes.Length);
cache.Close();




조금은 하드코딩이 되겠지만요 ^^;
제가 사용한 방법을 예를 들자면 에셋에서 그림파일을 불러온후
그것을 PNG로 변환 설정한후에 byte[]형으로 변환해서
FileStream을 사용해 Write해주는 방식으로 처리 했어요.



다른 한가지 방법으로는 zip를 이용해서 다운로드 한후 압축을 풀어 사용하는 방법도 있습니다.
전 요즘엔 이 방법을 더 많이 쓰는것 같군요 ^^;


zip 파일로 다운로드를 만든 경우에는 Object로 불러 오신후 그것을
(GameObject)Instantiate(불러온 오브젝트, 좌표, Quaternion회전) 등으로 사용할 수 있을듯 합니다.
테스트는 안해 봤어요 ^^;;







어셋 번들 만들기~
    public static string[] GetAssetNameList()

    {

        string[] assetName =

        {

            "assets/resources/object/mobobject/n2010_wolf/face/n2010f01.png",

            "assets/resources/object/mobobject/n2010_wolf/n2010.png",
             .....
        };
        m_strAssetNameList = assetName;

        return assetName;

    }
 
    [MenuItem("Assets/Build AssetBundles - Windows")]

    public static void BuildAssetWindows()

    {

        string[] assetName = AssetBundleModule.GetAssetNameList();
        Object[] asset = new Object[assetName.Length];

        for (int i = 0; i < assetName.Length; ++i)

        {

            asset[i] = AssetDatabase.LoadMainAssetAtPath(assetName[i]);

            assetName[i] = Regex.Replace(assetName[i], @"(?i)Assets/Resources/", "");

            assetName[i] = assetName[i].Remove(assetName[i].LastIndexOf("."));

            Debug.Log(assetName[i]);

        }
        Debug.Log("Make AssetBundle totalcount: " + assetName.Length.ToString());
        BuildPipeline.BuildAssetBundleExplicitAssetNames(asset, assetName, AssetBundleModule.GetAssetPrefixName() + "Windows" + AssetBundleModule.GetAssetPostfixName(), BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets, BuildTarget.StandaloneWindows);

    }
 
어셋 번들 로드하기~~
        if (m_bUseCache == true)

        {

            string assetPath = GetAssetBundleWebURL();

            Debug.Log(assetPath);

            m_WWW = WWW.LoadFromCacheOrDownload(assetPath, m_nAssetBundleVersion);

        }

        else

        {

            string assetPath = GetAssetBundlePath();

            Debug.Log(assetPath);

            m_WWW = new WWW(assetPath);

        }
 
로드다되면
        m_AssetBundle = m_WWW.assetBundle;

        m_WWW.Dispose();

        m_WWW = null;
 
어셋 찾아서 쓰기
            UnityEngine.Object findObject = m_AssetBundle.Load(name, type);

            if (findObject == null)

            {

                Debug.Log("FindAssetName not exists object : " + name + " / type : " + type.ToString());

            }

            return findObject;
 





http://botta.tistory.com/38 이 사이트를 참고하셔서 만들어보세요~ 그리고

    public IEnumerator OnLoadAssetBundle()
    {
        m_WWW = new WWW("file://" + Application.dataPath + "/../" + "애셋번들");
     
        yield return m_WWW;

        m_AssetBundle = m_WWW.assetBundle;

        m_WWW.Dispose();

        m_WWW = null;
       
       
        Texture m_Tex1 = (Texture)m_AssetBundle.Load("CFa0.png", typeof(Texture));
       

    }





C#을 기준으로 설명 드릴께요.
먼저 변수선언으로
int _gender = 0;
int _job = 0;
Texture2D _texture = null;
AssetBundle _assetBundle = null;
를 주시고,
함수 한개를 만들어서

IEnumerator gameHeroImageLoad (int argGender, int argJob) {
WWW _www = new WWW("file://" + "디렉토리와 파일명");
yield return _www;

_assetBundle = _www.assetBundle;
string _tmpHeroImageName = argGender + "-" + argJob + "-Texture";
if (_assetBundle.Gontains(_tmpHeroImageName)) {
_texture = (Texture2D)_assetBundle.Load(_tmpHeroImageName);
}
}

Update () 에서 특정 조건일때 위에 함수를 불러 오게되면 _texture에
이미지가 들어 가겠죠.
그후 OnGUI ()에서 _texture가 null일때와 아닐때의 표시 부분을 바꿔 주시면 될듯 합니다.
단 한가지 주의할 점은 그래픽을 다른 그래픽으로 바꾸시고 싶으시다면,
void deleteGameObject () {
_texture = null;
_assetBundle.Unload(true);
_assetBundle = null;
}
이 함수를 부르신 후에 다시 gameHeroImageLoad를 불러와 주시면 됩니다.
번들을 만들때는 이름에 주의 하셔서 성별-직업-Texture와 같이 png파일을 저장해 주시면 될 것 같습니다.
그냥 머리속의 프로그램을 적는 거니 버그가 있을 수 있습니다.










에셋번들 관련 링크


api


http://docs.unity3d.com/ScriptReference/AssetBundle.html


menual


http://docs.unity3d.com/Manual/AssetBundlesIntro.html



Trackback 0 And Comment 0
prev | 1 | next